Optional Type
Optional is a built-in type layer written as T?.
Basic Usage
Section titled “Basic Usage”Int? maybe = 123;_ same = maybe;
Bar? bar = Bar { x: 1, y: 2 }_ field = bar?.x;Optional Chaining
Section titled “Optional Chaining”Use ?. to access a field only when the receiver is not null:
_ value = user?.profile?.name;Conditional Unwrapping
Section titled “Conditional Unwrapping”Use is some:
if maybe is some value { print(value);} else { print(0);}Explicit inferred and mutable bindings:
if maybe is some _ value { print(value);}
if maybe is some _! value { value = value + 1;}??
?? provides a fallback value when the optional is empty:
Int value = maybe ?? 42;Int other = maybe ?? fallback();The left side must be optional. Use guard for early-exit control flow.
() print_value(Int? maybe) { guard maybe is some value else { return (); }
print(value); return ();}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:
Int value = maybe$.some();Ordinary code should prefer is some, guard, or ??.