Concept Flow - Nil coalescing operator (??)
Optional value
→Is it nil?
Yes
Use default value
The nil coalescing operator checks if an optional has a value; if yes, it uses that value, otherwise it uses a default.
let name: String? = nil let displayName = name ?? "Guest" print(displayName)
| Step | Variable | Value | Condition | Action | Output |
|---|---|---|---|---|---|
| 1 | name | nil | name == nil | Use default "Guest" | "Guest" |
| 2 | displayName | "Guest" | - | Assign displayName = "Guest" | - |
| 3 | - | - | - | Print displayName | Guest |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| name | nil | nil | nil | nil |
| displayName | undefined | undefined | "Guest" | "Guest" |
Syntax: optionalValue ?? defaultValue Behavior: Returns optionalValue if not nil; otherwise returns defaultValue. Use to provide fallback values for optionals. Example: let x = name ?? "Guest" Simple and safe way to handle nil optionals.
?? do in Swift??? returns the optional's value if it exists; otherwise, it returns the default value provided.?? between an optional and a default value.?? correctly: let value = optionalValue ?? defaultValue.var name: String? = nil let displayName = name ?? "Guest" print(displayName)
name is nil.name ?? "Guest" returns "Guest" because name is nil.let age: Int? = 25 let userAge = age ?? print(userAge)
?? must be followed by a default value to use if the optional is nil.age ?? is incomplete because no default value is provided after ??.let scores: [String: Int?] = ["Alice": 85, "Bob": nil], which expression correctly uses the nil coalescing operator to get Bob's score or 0 if nil?Int? inside the dictionary optional lookup, so scores["Bob"] returns Int??.scores["Bob"] ?? nil ?? 0 first flattens the double optional to Int? (returns inner value or nil), then applies ?? 0 to provide 0 if nil, yielding Int. For "Bob", some(nil) ?? nil = nil, then nil ?? 0 = 0.Pass the test and this pattern moves unknown