Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ?? (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

let result = optionalExpression ?? defaultExpression
Semantically, the ?? operator is a concise shorthand for the ternary conditional operator combined with forced unwrapping:
// The ?? operator
a ?? b

// Is equivalent to:
a != nil ? a! : b

Type Constraints

For the compiler to resolve the ?? operator, strict type constraints apply:
  1. The left-hand side (optionalExpression) must be of type Optional<T>.
  2. The right-hand side (defaultExpression) must evaluate to type T (the exact wrapped type of the left-hand side).
  3. The resulting expression evaluates to a non-optional T.
Note: It is syntactically valid for the right-hand side to also be an 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:
public func ?? <T>(
    optional: T?, 
    defaultValue: @autoclosure () throws -> T
) rethrows -> T
  • 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., when optional is .none).
  • rethrows: Propagates any errors thrown by the defaultValue expression, provided the expression is actually evaluated.
Master Swift with Deep Grasping Methodology!Learn More