0Pricing
Swift Academy · Lesson

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

  1. The Nil-Coalescing Operator
  2. Chaining Default Values
  3. Defaults in Function Parameters
  4. Dictionary Default Subscripts
← Back to Swift Academy