TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
?? (nil-coalescing) operator is a binary operator that unwraps an Optional<T> if it contains a value, or returns a fallback default value of type T if the optional evaluates to nil.
Syntax
?? operator is a concise shorthand for the ternary conditional operator combined with forced unwrapping:
Type Constraints
For the compiler to resolve the?? operator, strict type constraints apply:
- The left-hand side (
optionalExpression) must be of typeOptional<T>. - The right-hand side (
defaultExpression) must evaluate to typeT(the exact wrapped type of the left-hand side). - The resulting expression evaluates to a non-optional
T.
Optional<T>. In this scenario, the resulting expression remains an Optional<T>, allowing for nil-coalescing chains (a ?? b ?? c).
Short-Circuit Evaluation
The?? operator utilizes short-circuit evaluation. The right-hand side expression is evaluated lazily. If the left-hand side optional contains a value, the right-hand side is completely ignored and never executed.
This behavior is achieved in the Swift Standard Library by defining the defaultValue parameter as an @autoclosure.
Standard Library Signature
Under the hood, the operator is defined with the following function signature:T?: The optional value being evaluated.@autoclosure () throws -> T: The default value, wrapped in an automatic closure to defer execution until it is strictly necessary (i.e., whenoptionalis.none).rethrows: Propagates any errors thrown by thedefaultValueexpression, provided the expression is actually evaluated.
Master Swift with Deep Grasping Methodology!Learn More





