Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Mutating dictionaries

We saw in Chapter 2, Basic Swift that we can change a dictionary element's value like so:

dict["someKey"] = someValue 

Using the updateValue method instead returns the old value:

let oldThree = dict.updateValue("tree", forKey: "three") 
print("oldThree was", oldThree)
let oldFour = dict.updateValue("door", forKey: "four")
print("oldFour was", oldFour)

If we run the preceding code, we get the following debug console output:

oldThree was Optional("knee")
oldFour was nil

Since there was no element with the key "four", oldFour holds the value nil.