最新消息:VPS服务器又从fzhost.net换回Linode了,主题仍用朋友推荐的大前端D8

[已解决]swift中判断Dictionary中是否包含某个key键值

Swift crifan 137浏览 0评论

已有:

if extraParas is Dictionary<String, AnyObject> {

现在要去判断这个dict中是否已经存在某个 key,比如:

httpVerb

但是对于:

if let httpVerbStr = extraParas!["httpVerb"] {

结果已经是nil,却还是可以继续执行。。。

所以想要去搞清楚:

如何判断

Dictionary<String, AnyObject>

中是否存在某个key

试着找了下,没找到。

包括

isExisted

containKey之类的

但是都没找到。

swift dictionary has key

Determining if Swift dictionary contains key and obtaining any of its values – Stack Overflow

改为:

if let httpVerbStr = extraParas?["httpVerb"]

也不行。

swift dictionary contain key

if extraParas!.containsValueForKey("httpVerb") {

出错:

2015-12-10 14:47:27.940 JianDao[6710:263838] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[_TtGCSs29_NativeDictionaryStorageOwnerSSSS_ containsValueForKey:]: unrecognized selector sent to instance 0x7f9243e0b170’

swift dictionary contains key

swift dictionary check contains key

swift check contain key for dict

swift dict contains

Swift Dictionary: String and Int Lookups, Contains Keys

Traversing an array that contains dictionaries in Swift | Treehouse Community

The Swift Swift Tutorial: How to Use Dictionaries in Swift | Making App Pie

最后,确定:

应该还是编译器的bug,导致了,无法检测到对应的值:

            //if let httpVerbStr = extraParas?["httpVerb"] {
            if let httpVerbStr = extraParas!["httpVerb"] {
           
//if extraParas!["httpVerb"] != nil {
//            if extraParas!.containsValueForKey("httpVerb") {
//            let arrayOfKeys = extraParas!.allKeys
//            if arrayOfKeys.contains("httpVerb") {
//            let httpVerbStr = extraParas!["httpVerb"]
//            print("httpVerbStr=\(httpVerbStr)") //nil
//            if httpVerbStr != nil {
////                let httpVerbStr = extraParas!["httpVerb"]
                httpVerb = httpVerbStr as? String
               
print("httpVerb=\(httpVerb)") //POST
            }

extraParas!["httpVerb"]

得到的httpVerbStr

虽然是nil,但是代码仍会执行。。

print("httpVerbStr=(httpVerbStr)") //nil

if httpVerbStr != nil {

-》所以只能说明是编译器有问题。。。

算了,懒得理会了。。。

【总结】

最后还是变成之前的代码:

if let httpVerbStr = extraParas!["httpVerb"] {
                httpVerb = httpVerbStr as? String
               
print("httpVerb=\(httpVerb)") //POST
            }

即可。

转载请注明:在路上 » [已解决]swift中判断Dictionary中是否包含某个key键值

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
19 queries in 0.243 seconds, using 9.80MB memory