With Swift's Dictionary, why does dict[key] return an optional, and when do you use the default subscript, grouping or uniquing initializers?
answer
- the key may be missing
- count with a fallback value
- group values under a computed key
- duplicates trap or merge
basics
~10 sdict[key] returns Value? because the key may be absent, and assigning nil removes it. dict[key, default: v] supplies a fallback for counting; Dictionary(grouping:by:) buckets values; init(uniqueKeysWithValues:) traps on duplicate keys, while init(_:uniquingKeysWith:) merges them.
solid answer
~40 sA key lookup can miss, so `Dictionary`'s key subscript is typed `Value?`: `nil` on read means absent, and assigning `nil` removes the pair. When a missing key should behave like a starting value, `dict[key, default: 0] += 1` reads the default, mutates it and stores it in one step, which is the idiomatic counter; it works the same for `dict[key, default: []].append(x)`. `Dictionary(grouping:by:)` builds `[Key: [Element]]` from a sequence, keeping source order inside each array. `Dictionary(uniqueKeysWithValues:)` has a precondition of unique keys and traps on a duplicate, so for data you do not control I use `Dictionary(_:uniquingKeysWith:)` and say which value wins.
code
swift · 28 linesstruct Photo {
let id: Int
let album: String
let tags: [String]
}
let photos = [
Photo(id: 1, album: "Trip", tags: ["sea", "sun"]),
Photo(id: 2, album: "Home", tags: ["cat"]),
Photo(id: 3, album: "Trip", tags: ["sea"]),
]
var tagCounts: [String: Int] = [:]
for photo in photos {
for tag in photo.tags {
tagCounts[tag, default: 0] += 1 // inserts 0 the first time, then adds
}
}
print(tagCounts["sea"]!) // 2
let byAlbum = Dictionary(grouping: photos, by: { $0.album })
print(byAlbum["Trip"]!.map(\.id)) // [1, 3], source order kept
let pairs = photos.map { ($0.album, $0.id) }
let lastPerAlbum = Dictionary(pairs, uniquingKeysWith: { _, newer in newer })
print(lastPerAlbum["Trip"]!) // 3
// Dictionary(uniqueKeysWithValues: pairs) would trap here:
// "Fatal error: Duplicate values for key: 'Trip'"go deeper
Recall that a dictionary lookup gives an optional and that assigning nil removes the key. Know the counter idiom with the default subscript.
Explain how the default subscript mutates in place, why its default is an autoclosure, and which initializer traps on duplicate keys and which merges.
Treat any dictionary built from external data as possibly containing duplicate keys, and choose uniquingKeysWith with an explicit winner instead of a trapping initializer.
Set a team rule for building lookups from server data: duplicates are expected input, so the merge policy is written down rather than left to a crash.
## Why the subscript is optional `Dictionary<Key, Value>` declares its key-based subscript as `subscript(key: Key) -> Value?`. A dictionary cannot promise that a key is present, so the type forces the caller to handle absence: - **Reading** returns the stored value wrapped in an optional, or `nil` when the key is missing. - **Assigning a value** inserts the pair, or overwrites the existing value for that key. - **Assigning `nil`** removes the key and its value. That is why `let title: String = cache[id]` does not compile: Swift reports `value of optional type 'String?' must be unwrapped to a value of type 'String'` and offers `??` or `!` as fixes. Contrast this with `Array`, whose integer subscript returns `Element` directly and traps on an index outside `0..<count`. One subtle case: when `Value` is itself optional, such as `[String: Int?]`, a read returns `Int??`. The outer level says whether the key exists, the inner level is the stored value. Unwrapping rules for that are covered in the lesson on optionals. ## The default subscript `subscript(_:default:)` returns the stored value, or the `default` you pass when the key is missing, and its result is **not** optional. Its real value is mutation: ```swift var tagCounts: [String: Int] = [:] for tag in tags { tagCounts[tag, default: 0] += 1 } ``` The documentation describes exactly this: for a new key, the default value is returned from the subscript, incremented, and then added to the dictionary under that key. The same idiom builds dictionaries of arrays with `groups[key, default: []].append(item)`, and it mutates the stored array in place rather than copying it out and back. Two details matter: 1. The default parameter is an `@autoclosure`, so an expensive default is evaluated only when the key is missing. 2. The documentation warns not to use this subscript to modify values when `Value` is a **class**: the default instance and key are not written back after the operation, so a mutation of a fresh default object is lost. ## Building dictionaries from sequences | Initializer | Duplicate keys | Result | |---|---|---| | `Dictionary(uniqueKeysWithValues:)` | **traps**: precondition that keys are unique | `[Key: Value]` | | `Dictionary(_:uniquingKeysWith:)` | your closure combines old and new values | `[Key: Value]` | | `Dictionary(grouping:by:)` | collected into one array per key | `[Key: [Element]]` | - **`Dictionary(uniqueKeysWithValues:)`** is right only when uniqueness is guaranteed, such as zipping a list of known IDs with values. A duplicate stops the process with `Fatal error: Duplicate values for key: 'Trip'`. A dictionary *literal* with a repeated key traps at run time too, with `Dictionary literal contains duplicate keys`. - **`Dictionary(_:uniquingKeysWith:)`** takes a closure `(Value, Value) -> Value` that receives the existing value and the new one; `{ _, newer in newer }` keeps the last, `{ older, _ in older }` the first, `+` sums. `merge(_:uniquingKeysWith:)` does the same for an existing dictionary. - **`Dictionary(grouping:by:)`** runs your closure on each element to compute its key and collects elements into arrays. Each array has at least one element, in the same order as the source sequence. ## Neighbouring Dictionary APIs worth naming - `updateValue(_:forKey:)` stores a value and returns the **old** value, or `nil` when the key was new, which tells you whether you inserted or replaced. - `removeValue(forKey:)` removes a key and returns the removed value, or `nil` when it was absent. - `merge(_:uniquingKeysWith:)` and `merging(_:uniquingKeysWith:)` combine two dictionaries with the same duplicate policy as the initializer. - `keys` and `values` are views over the dictionary, in the same unpredictable order as the dictionary itself. - `Dictionary(minimumCapacity:)` pre-sizes storage when you know roughly how many pairs you will insert. ## Applying it to a gallery For a photo library, counting tags uses the default subscript, grouping photos by album uses `Dictionary(grouping:by:)`, and building an ID-to-photo cache from server data uses `uniquingKeysWith`, because a server that returns the same ID twice should not crash the app. The code example runs all three. ## Interview shape State why the subscript is optional, show the counting idiom, and say which initializer traps. Interviewers often follow up by handing you a server list with a repeated ID and asking what `uniqueKeysWithValues` does with it; the answer is a run-time trap, not a dropped value.
- What does `cache[id] = nil` do when the dictionary's Value type is `String?`?It removes the key, because the subscript's own optional is set to `nil`. To store a `nil` value under the key you write `cache[id] = .some(nil)` or use `updateValue(nil, forKey: id)`.
- Why is the default parameter of `subscript(_:default:)` an autoclosure?So the default expression is evaluated only when the key is missing. An expensive default, such as creating an empty buffer or loading a placeholder, costs nothing on a hit.
- How would you keep the most recent value when building a dictionary from a list with repeated IDs?Use `Dictionary(pairs, uniquingKeysWith: { _, newer in newer })`. The closure receives the existing value and the new one for each duplicate, so returning the second keeps the latest in sequence order.
- Expecting dict[key] to trap on a missing key like an array index
- Thinking Dictionary(uniqueKeysWithValues:) silently keeps the last duplicate
- Using the default subscript to mutate class-typed values and expecting it stored
- Expecting Dictionary(grouping:by:) to sort the elements in each group
- Reading the value, unwrapping, mutating and reassigning for every counter update