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:
Syntax
let result = optionalValue ?? defaultValue
let result = first ?? second ?? defaultValue
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
// Declare a constant `userInput` (a `String?`), set to `nil`
let userInput: String? = nil
// Declare a constant `displayName`, set to `userInput ?? "Guest"`
let displayName = userInput ?? "Guest"
// Print "Welcome, \(displayName)" to the console
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
// Declare a constant `primary` (a `String?`), set to `nil`
let primary: String? = nil
// Declare a constant `secondary` (a `String?`), set to `nil`
let secondary: String? = nil
// Declare a constant `fallback`, set to `"[email protected]"`
let fallback = "[email protected]"
// Declare a constant `email`, set to `primary ?? secondary ?? fallback`
let email = primary ?? secondary ?? fallback
// Print "Using email: \(email)" to the console
print("Using email: \(email)")
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: