Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How setting 'nil' as a value of [String: String] dictionary is valid?

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?] ?

like image 312
Robert Avatar asked Apr 11 '18 10:04

Robert


People also ask

Can a dictionary have a null value?

Dictionaries can't have null keys.

Can a dictionary have a null as a key?

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.

Can a dictionary be null C#?

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.

Are Dictionary values optional Swift?

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 .


1 Answers

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.

like image 152
Milan Nosáľ Avatar answered Nov 15 '22 05:11

Milan Nosáľ