Introduction
Often you just want to use an optional's value if it exists, and fall back to some default otherwise. Writing a full if let ... else block for this every time is verbose. The nil coalescing operator ?? compresses that pattern into a single expression: it returns the optional's unwrapped value if it is non-nil, or a default value you supply if it is nil.
Cricket analogy: Instead of writing a full over of if-else commentary to decide a fallback batting order, ?? is like a captain who instantly slots in the reserve opener if the regular one is unavailable, collapsing the whole decision into one quick substitution.
Syntax
let value = optionalValue ?? defaultValueExplanation
optionalValue ?? defaultValue is shorthand for: 'if optionalValue contains a value, unwrap and use it; otherwise, use defaultValue.' The type of defaultValue must match the wrapped type of optionalValue (a non-optional type), and the result of the whole expression is always non-optional. This is exactly equivalent to writing optionalValue != nil ? optionalValue! : defaultValue, but far safer and more readable since it avoids force unwrapping entirely. You can also chain multiple ?? operators to fall through several optionals in sequence.
Cricket analogy: selectedOpener ?? reserveOpener unwraps the chosen opener if picked, otherwise slots in the reserve, exactly equivalent to selectedOpener != nil ? selectedOpener! : reserveOpener but without risking a crash from force-unwrapping a batsman who never turned up; you can even chain ?? thirdChoice for a deeper bench.
Example
var storedName: String? = nil
var displayName: String? = "Guest"
let greetingName = storedName ?? displayName ?? "Anonymous"
print("Welcome, \(greetingName)!")
var customTimeout: Int? = 30
let timeout = customTimeout ?? 60
print("Timeout: \(timeout)")Output
Welcome, Guest!
Timeout: 30Key Takeaways
optionalValue ?? defaultValuereturns the unwrapped value if present, otherwise the default.- The result of a
??expression is always a non-optional type. - It is shorthand for an if-let/else pattern, without needing force unwrapping.
- Multiple
??operators can be chained to try several fallbacks in order. - The default value's type must match the optional's wrapped type.
Practice what you learned
1. What does `let value = optionalValue ?? defaultValue` do?
2. What is the type of the result of `a ?? b` where a is `Int?` and b is `Int`?
3. Which is equivalent to `optionalValue ?? defaultValue`?
4. Can nil coalescing operators be chained, like `a ?? b ?? c`?
5. What must be true about the default value's type in `optionalValue ?? defaultValue`?
Was this page helpful?
You May Also Like
Optionals in Swift
Optionals let a Swift variable represent either a value or the absence of one, forming the basis of Swift's null-safety.
Optional Binding in Swift
Optional binding safely unwraps an optional's value into a local constant only when a value is actually present.
Operators in Swift
Understand Swift's arithmetic, comparison, logical, and range operators, and how the closed and half-open range operators differ.
The guard Statement in Swift
The guard statement performs early-exit validation, unwrapping optionals for use in the rest of the enclosing scope.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics