Nil Coalescing Operator
The nil coalescing operator (??) says "use this value, but if it's missing, use this other backup value instead."
In this page:
Basic Nil Coalescing
The ?? operator returns the optional's value if present, or a default value if the optional is nil, all in one concise expression.
Example: Basic Nil Coalescing
let userInput: String? = nil
let displayName = userInput ?? "Guest"
print("Welcome, \(displayName)")
Login to try C/C++/Java/PHP code in the editor
Nil Coalescing with Chained Fallbacks
?? can be chained so that if the first optional is nil, the second is tried, and so on, down to a final guaranteed default.
Example: Nil Coalescing with Chained Fallbacks
let primary: String? = nil
let secondary: String? = nil
let fallback = "[email protected]"
let email = primary ?? secondary ?? fallback
print("Using email: \(email)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using an
if-elseblock just to provide a fallback default when??would express the same logic in one line. - Forgetting that the right-hand side of
??must match the optional's wrapped type (or be another optional of that type). - Chaining
??incorrectly assuming operator precedence works differently than left-to-right with the rest of an expression -- parentheses help clarify complex expressions.
Chapter Summary
a ?? bevaluates toaif it's non-nil, orbotherwise.??provides a clean, single-line way to supply default values for optionals.- The fallback value on the right must be of the same (non-optional) type as the optional's wrapped value.
??can be chained:a ?? b ?? ctries each in turn.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: