Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am currently using the following (clumsy) pieces of code for determining if a (non-empty) Swift dictionary contains a given key and for obtaining one (any) value from the same dictionary.

How can one put this more elegantly in Swift?

// excerpt from method that determines if dict contains key if let _ = dict[key] {     return true } else {     return false }  // excerpt from method that obtains first value from dict for (_, value) in dict {     return value } 
like image 341
Drux Avatar asked Jan 24 '15 19:01

Drux


People also ask

How do you check if a dictionary contains a key in Swift?

Swift – Check if Specific Key is Present in Dictionary To check if a specific key is present in a Swift dictionary, check if the corresponding value is nil or not. If myDictionary[key] != nil returns true, the key is present in this dictionary, else the key is not there.

How do you check if a dictionary contains a key?

Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How do you check if a dictionary is empty or not in Swift?

To check if a dictionary is empty, you can either check if the size of the dictionary is zero or use the isEmpty function. The type of keys array is same as that of keyType , and the type of values array is same as that of valueType .

How do I compare dictionaries in Swift?

Without custom type in value of Dictionary, in Swift 2+ you can use the == operator to compare two Dictionary to check if they are equal or not. But in some cases with custom types as the Dictionary 's value (like struct ), you must adopt Equatable in order for that custom type to use == operator.


2 Answers

You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value).

So, if you just want to answer the question whether the dictionary contains the key, ask:

let keyExists = dict[key] != nil 

If you want the value and you know the dictionary contains the key, say:

let val = dict[key]! 

But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:

if let val = dict[key] {     // now val is not nil and the Optional has been unwrapped, so use it } 
like image 70
matt Avatar answered Oct 09 '22 09:10

matt


Why not simply check for dict.keys.contains(key)? Checking for dict[key] != nil will not work in cases where the value is nil. As with a dictionary [String: String?] for example.

like image 34
Hans Terje Bakke Avatar answered Oct 09 '22 09:10

Hans Terje Bakke