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
- Look up the key with
phoneBook[name], which gives aString?. - Unwrap it with
!, the force-unwrap operator. It turns theString?into aString. - 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 isnilstops the program with a run-time error. The lesson guarantees thatnameis always a key, so the optional is nevernil. When a key might be missing, useif let,guard letor??instead. - Exact keys. Dictionary keys match exactly, so
"ben"is not"Ben". - The type.
[String: String]is shorthand forDictionary<String, String>. The value type isStringhere, so the subscript givesString?.
Edge cases and common mistakes
- Returning the optional.
return phoneBook[name]without!doesn't compile, because the function's return type isString, notString?. - 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".
