Why does reading a key from a Swift dictionary typed [String: String?] give String??, and how do you tell a missing key from a stored nil?
answer
- the subscript adds its own level
- outer nil versus inner nil
- writing nil deletes
- ?? peels one level
basics
~20 sDictionary's subscript returns Value?, and Value is already String?, so the read is String??: nil means the key is missing, .some(nil) means it holds nil. Match both levels, and store nil with updateValue(_:forKey:), because assigning nil removes the key.
solid answer
~40 s`Dictionary.subscript(_:)` returns `Value?` so it can report "no such key". With `Value == String?` that becomes `Optional<Optional<String>>`: `.none` is a missing key, `.some(.none)` is a key that is present and holds `nil`. So `middleNames["ana"] == nil` is `false` when `"ana"` maps to `nil`. Tell them apart with a `switch` on `.none`, `.some(.none)` and `.some(.some(let name))`, or with `if let entry = middleNames[key]`, which strips only the outer level and leaves `entry` as `String?`. Writing has its own trap: `middleNames[key] = nil` removes the key, so store an explicit `nil` with `middleNames[key] = .some(nil)` or `updateValue(nil, forKey:)`. And `??` unwraps one level only: `middleNames[key] ?? "none"` is still a `String?` and gives `nil` for a stored `nil`.
code
swift · 23 lines// Middle names from a backend: a key present with nil means "no middle name";
// a missing key means "not loaded yet".
var middleNames: [String: String?] = ["ana": nil, "rui": "Miguel"]
print(type(of: middleNames["ana"])) // Optional<Optional<String>>
print(middleNames["ana"] == nil) // false: the key exists
print(middleNames["bo"] == nil) // true: the key is missing
switch middleNames["ana"] {
case .none: print("ana: not loaded")
case .some(.none): print("ana: has no middle name")
case .some(.some(let m)): print("ana: \(m)")
}
middleNames["rui"] = nil // removes the key
middleNames["cy"] = .some(nil) // stores an explicit nil
middleNames.updateValue(nil, forKey: "dee") // also stores nil
print(middleNames.keys.sorted()) // ["ana", "cy", "dee"]
let label = middleNames["ana"] ?? "none" // String?, still nil
print(type(of: label), label as Any) // Optional<String> nil
let flattened: String? = middleNames["ana"] ?? nil
print(flattened as Any) // nilgo deeper
Recall that a dictionary lookup returns an optional because the key may be missing, and that values which are themselves optional add a second level.
Explain the three states of String??, show how a switch or an outer binding tells them apart, and why ?? with a String default leaves a String?.
Diagnose the bug where nil assignment deletes a key or a nil comparison misfires, and fix it with .some(nil), updateValue or an explicit two-level match.
Decide when a two-level optional is acceptable in a model and when the states deserve an enum, so that absent and unknown never get confused across a team.
## Where the second level comes from A Swift `Dictionary<Key, Value>` lookup through `subscript(_:)` returns `Value?`. The extra optional is how the dictionary says **"this key is not here"**. Usually `Value` is non-optional, so a lookup gives a single optional and nobody thinks about it. Now model data decoded from a backend where some users explicitly have **no** middle name (the field came back as `null`) and others have not been loaded yet: ```swift var middleNames: [String: String?] = ["ana": nil, "rui": "Miguel"] ``` Here `Value` is `String?`, so a lookup returns `String??`, which is `Optional<Optional<String>>`. Three states now exist: | Value of `middleNames[key]` | Meaning | |---|---| | `.none` | the key is not in the dictionary | | `.some(.none)` | the key is present and its value is `nil` | | `.some(.some("Miguel"))` | the key is present with a middle name | Because the outer level is `.some` when the key exists, `middleNames["ana"] == nil` is **`false`**, even though Ana has no middle name. Code written for a non-optional dictionary silently changes meaning. ## Reading: telling the two nils apart There are three idiomatic ways: 1. **Match both levels** with `switch`: `case .none`, `case .some(.none)`, `case .some(.some(let name))`. This is the most explicit and is the right choice when all three states need different handling. 2. **Bind the outer level** with `if let entry = middleNames[key]`. The binding strips one level, so `entry` is a `String?`: you know the key exists and can then test `entry` itself. 3. **Chain the bindings** in one condition list: `if let entry = middleNames[key], let name = entry { … }` runs only when both levels hold values. ## Writing: nil removes the key The subscript setter takes `Value?` too, and the standard library documents that assigning `nil` **removes** the key and its value. With an optional `Value` this bites hard: - `middleNames["rui"] = nil` deletes Rui's entry instead of recording "no middle name". - `middleNames["cy"] = .some(nil)` stores an explicit `nil` value. - `middleNames.updateValue(nil, forKey: "dee")` also stores `nil`, because its parameter is `Value`, not `Value?`. ## ?? and flattening `??` unwraps **one** level. With `String??` on the left and a `String` literal on the right, the compiler picks `T == String?`, so `middleNames["ana"] ?? "none"` is a `String?` holding `nil`: the default is not used, because the outer level was `.some`. To collapse the two levels deliberately, use `middleNames[key] ?? nil` or `middleNames[key].flatMap { $0 }`, which give a `String?` that is `nil` for both a missing key and a stored `nil`. Do that only where the difference no longer matters. ## Other places nested optionals appear - `Optional.map` with a closure that returns an optional gives `U??`; `flatMap` avoids it. - `try?` on a call that returns an optional used to produce a double optional; since Swift 5 (SE-0230) it flattens to a single level, so older answers about `Int??` from `try?` are out of date. - Generic code where a type parameter is itself bound to an optional, which is exactly how the dictionary case arises. ## Asking only whether the key exists Sometimes the question is presence alone. `middleNames.keys.contains(key)` and `middleNames.index(forKey: key) != nil` answer it without touching the value. The defaulting subscript `subscript(_:default:)` goes the other way: `middleNames[key, default: nil]` returns `Value`, here `String?`, so a missing key and a stored `nil` both come back as `nil`. That is convenient for display and wrong for any logic that must tell "unknown" from "known to be absent". ## A design note A dictionary of optionals is a legitimate way to keep "known to be absent" apart from "unknown", but it is easy to misread. When the states carry meaning for the product, a small enum with named cases states them more clearly than two levels of `Optional`, and readers do not have to remember which `nil` is which.
- How do you collapse String?? to String? when the difference between the two nils no longer matters?Write `middleNames[key] ?? nil`, which unwraps the outer level and uses `nil` as the default, so the result is a `String?`, or `middleNames[key].flatMap { $0 }`, which returns the inner optional as is. Both give `nil` for a missing key and for a stored `nil`, so do it only after any code that needed to distinguish them.
- Does try? on a function that returns Int? still produce a double optional?Not since Swift 5. SE-0230 changed `try?` so that, applied to an expression that is already optional, it flattens the result instead of wrapping it again; `try? parse("4")` on a `throws -> Int?` function is an `Int?`. The nested result described in older material came from Swift 4 behaviour.
- dict[key] == nil always means the key is absent, whatever the value type.
- Assigning nil through the dictionary subscript stores nil for that key.
- The ?? operator unwraps every level of a nested optional at once.
- if let entry = dict[key] gives a non-optional String when the values are String?.
- try? on a call returning Int? still yields Int?? in Swift 5 and later.