Problem overview
The function safeLookup receives scores, a dictionary of type [String: Int] from names to scores, and a name. It returns the score of name, or 0 when name isn't a key.
With scores = ["Ana": 90, "Ben": 75, "Cara": 88], looking up "Ben" gives 75 and looking up "Dan" gives 0. An empty dictionary has no keys, so every name gives 0. Matching is exact: "ana" is not a key when the dictionary holds "Ana".
Approach
A plain lookup, scores[name], returns an Int?: the score when the key exists and nil when it doesn't. For the missing name "Dan", printing scores["Dan"] shows nil. The function has to return an Int, so something must turn nil into 0.
Swift dictionaries have a second subscript for this: scores[name, default: 0]. It returns the stored value when the key exists and the default otherwise. The result is a plain Int, so no unwrapping is needed.
Swift makes you decide what a missing key means. Many languages return a special value or raise an error on their own. Swift's plain subscript hands the decision back to you through the optional type: you can't use the score until you've said what happens when it isn't there. The default: subscript is the shortest way to say it when a fixed fallback value makes sense, like 0 for a name with no score.
The two forms print differently, which shows the difference in type. For a name that exists, scores["Ben"] prints Optional(75), while scores["Ben", default: 0] prints 75.
Step by step
The lesson has one step: return the value of name read with the default: subscript, using 0 as the default.
The solution in Swift
class Solution {
func safeLookup(_ scores: [String: Int], _ name: String) -> Int {
return scores[name, default: 0]
}
}
Details to keep in mind:
- The default doesn't change the dictionary. When you only read, a missing key is not added. The default is just the value you get back.
- Another way:
??.scores[name] ?? 0gives the same result. It reads the optional and falls back to 0 when it isnil. Use whichever reads better to you. - Why not
!? Force-unwrappingscores[name]!stops the program with a run-time error when the key is missing, and this lesson says some names are missing. - A stored 0 is not a missing key. A score of 0 stays 0 either way, so a default of 0 can't tell the two cases apart. That is fine here, since both answers are 0.
Edge cases and common mistakes
- An empty dictionary.
[:]is the empty dictionary literal, and the lookup returns 0. - Different capitalization. With the keys above,
"ana"returns 0, because keys are compared exactly. - Returning the optional.
return scores[name]doesn't compile, because the return type isInt. - Force-unwrapping. It works for names that exist and crashes for the others.
Testing
["Ana": 90, "Ben": 75, "Cara": 88],"Ben"gives 75.- The same dictionary with
"Dan"gives 0. - The same dictionary with
"ana"gives 0. [:]with"Ana"gives 0.
