Check if key exists in dictionary of type [Type:Type?]

后端 未结 6 1798
时光说笑
时光说笑 2020-12-03 09:48

How can I check if a key exists in a dictionary? My dictionary is of type [Type:Type?].

I can\'t simply check dictionary[key] == nil, as th

6条回答
  •  伪装坚强ぢ
    2020-12-03 10:26

    I believe the Dictionary type's indexForKey(key: Key) is what you're looking for. It returns the index for a given key, but more importantly for your proposes, it returns nil if it can't find the specified key in the dictionary.

    if dictionary.indexForKey("someKey") != nil {
        // the key exists in the dictionary
    }
    

    Swift 3 syntax....

    if dictionary.index(forKey: "someKey") == nil {
        print("the key 'someKey' is NOT in the dictionary")
    }
    

提交回复
热议问题