0Pricing
Swift Academy · Lesson

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

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