Optional Type
Optional values are written as T?. The compiler-owned nominal name behind this form is not
available to user source.
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 .some(...) to unwrap a present value and .none to match an empty optional:
if maybe is .some(value) { print(value);} else { print(0);}Mutable and borrowed payload bindings:
if maybe is .some(Int value!) { value = value + 1;}
if maybe is .some(ref Int value) { print(value$.get());}??
?? 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 .some(...) patterns, guard, or ??.