Start learning free

LESSON 131 OF 292 · DICTIONARIES - CHALLENGES

Phone Book Lookup in Swift: Dictionary Subscript and !

Practice Read the full explanation

Given a phone book phoneBook, a Dictionary from names to phone numbers, and a name, return the phone number of name.

Every name in the phone book is a key, and its value is that person's phone number, a string like "555-0142". The name you look up is always in the phone book.

 

Example 1:

Input: phoneBook = {"Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"}, name = "Ben"
Output: "555-0199"
Explanation: The key "Ben" maps to "555-0199".

Example 2:

Input: phoneBook = {"Max": "555-0100"}, name = "Max"
Output: "555-0100"
Explanation: The phone book has a single entry, and it is the one we look up.

Example 3:

Input: phoneBook = {"Tom": "555-0111", "Tim": "555-0111"}, name = "Tim"
Output: "555-0111"
Explanation: Tom and Tim share a phone number. We only need the value of the key "Tim".

 

Constraints:

  • phoneBook has at least one entry.
  • name is always a key of phoneBook.
  • Names are single words made of English letters, and they are all different. Two people can share a phone number.
  • Every phone number is a string of three digits, a dash and four digits, like "555-0142".
STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · DICTIONARIES - CHALLENGES

    Phone Book Lookup in Swift, explained

    Problem overview

    The function phoneBookLookup receives phoneBook, a dictionary of type [String: String] that maps names to phone numbers, and a name. It returns that person's phone number. The name is always a key of the dictionary.

    With phoneBook = ["Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"] and name = "Ben", the answer is "555-0199". Two names may share a number: looking up "Tim" in ["Tom": "555-0111", "Tim": "555-0111"] returns "555-0111", because only the value stored under the key you ask for matters.

    Approach

    A dictionary finds a value from its key directly, with no loop. In Swift you write the key in square brackets after the dictionary: phoneBook[name].

    The subtlety is the type of that expression. A key might be missing, so Swift can't promise a String. The subscript returns an optional, String?, which holds either the value or nil. Printing phoneBook["Ben"] shows Optional("555-0199"), and printing phoneBook["Zed"] shows nil. The function must return a plain String, so the optional has to be unwrapped.

    It helps to see a dictionary as a table with two columns. The left column holds the keys, here the names, and each key appears once. The right column holds the values, here the numbers, and values can repeat. A lookup starts from the left column and returns the matching cell of the right column. You never have to walk through the entries one by one, and the size of the phone book doesn't change how you write the lookup.

    The exclamation mark is a promise to the compiler: "this optional has a value". The lesson makes that promise true by guaranteeing the name is in the book. If you later write code where that isn't guaranteed, replace the ! with a safer way to unwrap.

    Step by step

    1. Look up the key with phoneBook[name], which gives a String?.
    2. Unwrap it with !, the force-unwrap operator. It turns the String? into a String.
    3. Return the result. The whole lesson is one line.

    The solution in Swift

    class Solution {
        func phoneBookLookup(_ phoneBook: [String: String], _ name: String) -> String {
            return phoneBook[name]!
        }
    }
    

    Details worth knowing:

    • Why ! is acceptable here. Force-unwrapping an optional that is nil stops the program with a run-time error. The lesson guarantees that name is always a key, so the optional is never nil. When a key might be missing, use if let, guard let or ?? instead.
    • Exact keys. Dictionary keys match exactly, so "ben" is not "Ben".
    • The type. [String: String] is shorthand for Dictionary<String, String>. The value type is String here, so the subscript gives String?.

    Edge cases and common mistakes

    • Returning the optional. return phoneBook[name] without ! doesn't compile, because the function's return type is String, not String?.
    • A single entry. ["Max": "555-0100"] with "Max" works like any other dictionary.
    • Shared numbers. Values can repeat, but keys can't. A lookup by key always has one answer.
    • Using ! on an uncertain lookup. It is fine for this lesson's guaranteed key, and a crash for a missing one.

    Testing

    • ["Ana": "555-0142", "Ben": "555-0199", "Cara": "555-0123"], "Ben" gives "555-0199".
    • ["Tom": "555-0111", "Tim": "555-0111"], "Tim" gives "555-0111".
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free