The Nil-Coalescing Operator
Supply a default when an optional is nil.
The Problem of nil
An optional may hold a value or be nil. Often you want to use the value if present, or fall back to a default if it is nil.
let typedName: String? = nil
let name = typedName ?? "Guest"
print(name)The ?? Operator
The nil coalescing operator ?? takes an optional on the left and a default on the right. If the optional is non-nil, you get its unwrapped value; otherwise you get the default.
let stored: Int? = 42
let value = stored ?? 0
print(value)All lessons in this course
- The Nil-Coalescing Operator
- Chaining Default Values
- Defaults in Function Parameters
- Dictionary Default Subscripts