- Mastering macOS Programming
- Stuart Grimshaw
- 82字
- 2021-07-02 22:54:40
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.