Optional Type
Optional values are written as T?.
Basic Usage
Section titled “Basic Usage”Equality
Section titled “Equality”Optional equality is symmetric. If T is equatable, both T? == T and T == T? are valid, as are
the corresponding != forms. .none never equals a payload; .some(value) compares its payload.
Optional Chaining
Section titled “Optional Chaining”Use ?. to access a field only when the receiver is not null:
Conditional Unwrapping
Section titled “Conditional Unwrapping”Use .some(...) to unwrap a present value and .none to match an empty optional:
Mutable and borrowed payload bindings:
??
?? provides a fallback value when the optional is empty:
The left side must be optional. Use guard for early-exit control flow.
The else block must be non-empty and end in return, break, continue, or throw.
Force Unwrap
Section titled “Force Unwrap”optional$.some() force unwraps an optional through the implicit operation layer:
Ordinary code should prefer .some(...) patterns, guard, or ??.