Back to questions
JuniorTheoryCommon
What does the program print?
let stock = ["apples": 3, "pears": 0]
let apples = stock["apples"] ?? -1
let pears = stock["pears"] ?? -1
let plums = stock["plums"] ?? -1
print(apples, pears, plums)3 0 -1
- Expecting a crash, as with an array index past the end. A dictionary lookup of a missing key gives
nil, and??replaces it with-1. - Expecting
-1for"pears": treating a stored0as an empty value.??replaces onlynil, and the key"pears"exists.
- How can you check whether the key
"pears"is in the dictionary at all? - What does
stock["plums", default: -1]give, and does it add the key?