Start learning free

LESSON 133 OF 292 · DICTIONARIES - CHALLENGES

Safe Lookup in Swift: Dictionary default Subscript

Practice Read the full explanation

Given a Dictionary scores from names to scores and a name, return the score of name, or 0 when name isn't a key of scores.

Some names you look up aren't in the dictionary at all. They have no score, so the answer for them is 0.

 

Example 1:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Ben"
Output: 75
Explanation: "Ben" is a key of scores, and its value is 75.

Example 2:

Input: scores = {"Ana": 90, "Ben": 75, "Cara": 88}, name = "Dan"
Output: 0
Explanation: "Dan" isn't a key of scores, so the answer is 0.

Example 3:

Input: scores = {}, name = "Ana"
Output: 0
Explanation: An empty dictionary has no keys at all.

 

Constraints:

  • scores can be empty.
  • Names are single words made of English letters, and the names in scores are all different.
  • name matches a key only when it is spelled exactly the same, upper and lower case included: "ana" is not "Ana".
  • Every score is between 0 and 100.
STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · DICTIONARIES - CHALLENGES

    Safe Lookup in Swift, explained

    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] ?? 0 gives the same result. It reads the optional and falls back to 0 when it is nil. Use whichever reads better to you.
    • Why not !? Force-unwrapping scores[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 is Int.
    • 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.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free