Check If Key Exists In Dictionary Of Type [Type:Type?]


Answer :

Actually your test dictionary[key] == nil can be used to check if a key exists in a dictionary. It will not yield true if the value is set to nil:

let dict : [String : Int?] = ["a" : 1, "b" : nil]  dict["a"] == nil // false,     dict["a"] is .Some(.Some(1)) dict["b"] == nil // false !!,  dict["b"] is .Some(.None) dict["c"] == nil // true,      dict["c"] is .None 

To distinguish between "key is not present in dict" and "value for key is nil" you can do a nested optional assignment:

if let val = dict["key"] {     if let x = val {         println(x)     } else {         println("value is nil")     } } else {     println("key is not present in dict") } 

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") } 

You can always do:

let arrayOfKeys = dictionary.allKeys if arrayOfKeys.containsObject(yourKey) {  } else { } 

However I really dislike the idea of creating an NSDictionary which can contain optionals.


Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Change The Font Size Of Visual Studio Solution Explorer