Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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 that could result from the value being nil.

Any ideas?

like image 743
vrwim Avatar asked Mar 27 '15 11:03

vrwim


People also ask

How do you see if a key exists in a dictionary?

How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.

Which operator tests to see if a key exists in a dictionary?

The simplest way to check if a key exists in a dictionary is to use the in operator. It's a special operator used to evaluate the membership of a value. This is the intended and preferred approach by most developers.

How do you check if a value is a key in a dictionary Python?

To get the value for the key, use dict[key] . dict[key] raises an error when the key does not exist, but the get() method returns a specified value (default is None ) if the key does not exist.


2 Answers

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") } 
like image 163
Martin R Avatar answered Oct 12 '22 17:10

Martin R


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") } 
like image 35
Mick MacCallum Avatar answered Oct 12 '22 17:10

Mick MacCallum