A dictionary is an array of key: value
pairs. If you try accessing a dictionary for a key that does not exist it will return nil
.
For return type consistency (think of it as a return value from a function) the type returned from a dictionary has to be an optional. Whether it is a real value or nil, the return has to handle both.
In the case of arrays, you define whether the elements are optional or not. You will either allow a nil
value, or not. Up to you.
Try this in Playground. Note: for the print statements you will see warnings that Int?
has been coerced as Any
.
var myDictionary: [String: Int] = [:]
myDictionary["One"] = 1
print (myDictionary["One"])
myDictionary["One"] = 2
print (myDictionary["One"])
print (myDictionary["Two"])
print (myDictionary)
You will see that the first print with the key "One" will print out 1
, and the second print will be 2
(because the key was found in the the dictionary and the corresponding value was changed to 2.
The third print statement uses a key that does not exist in myDictionary
, and so the value returned is nil
.
The final print statement shows the whole of myDictionary
, which in this case is ["One": 2]
.