I'm curious why this snippet works correctly in Playground:
var dict = [String: String]()
dict["key"] = nil
let value = dict["key"]
we can see that I declared Dictionary with non optional values, after checking it in Playground it works similarly to dictionary declared as [String: String?]
My question is where is the difference in terms of setting nil
value between dictionary declared as [String: String]
and [String: String?]
?
Dictionaries can't have null keys.
Dictionary will hash the key supplie to get the index , in case of null , hash function can not return a valid value that's why it does not support null in key.
In the same way, cities is a Dictionary<string, string> type dictionary, so it can store string keys and string values. Dictionary cannot include duplicate or null keys, whereas values can be duplicated or null.
Dictionary accessor returns optional of its value type because it does not "know" run-time whether certain key is there in the dictionary or not. If it's present, then the associated value is returned, but if it's not then you get nil .
dict["key"] = nil
is a shorthand to removing the key from the dictionary (same as using dict.removeValue(forKey: "key")
). If there was a value under the "key"
key, after this line the whole entry is removed from the dictionary (both the key and the value).
Read the subscripts docs to learn more:
If you assign nil as the value for the given key, the dictionary removes that key and its associated value.
In the following example, the key-value pair for the key "Aquamarine" is removed from the dictionary by assigning nil to the key-based subscript.
hues["Aquamarine"] = nil print(hues) // Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]"
let value = dict["key"]
gets the value for the key, and by definition returns nil
if there is no entry for the given key (which is in your case).
According to docs, subscript returns either the value, or nil, if the key is not in the dictionary:
The value associated with key if key is in the dictionary; otherwise, nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With