Chaining Default Values
Combine multiple fallbacks cleanly.
More Than One Fallback
Sometimes you have several optional sources and want the first non-nil one. You can chain multiple ?? operators together.
let primary: String? = nil
let secondary: String? = "Backup"
let name = primary ?? secondary ?? "Default"
print(name)How Chaining Reads
Read a ?? b ?? c as: use a if it is non-nil, otherwise b, otherwise c. Evaluation stops at the first value found.
let a: Int? = nil
let b: Int? = nil
let c = 7
print(a ?? b ?? c)All lessons in this course
- The Nil-Coalescing Operator
- Chaining Default Values
- Defaults in Function Parameters
- Dictionary Default Subscripts