← Back to Swift Course | Chapter 5: Optionals | Lesson 6 of 8

Nil Coalescing Operator

The nil coalescing operator (??) says "use this value, but if it's missing, use this other backup value instead."

Basic Nil Coalescing

The ?? operator returns the optional's value if present, or a default value if the optional is nil, all in one concise expression.

Example: Basic Nil Coalescing

markup
let userInput: String? = nil
let displayName = userInput ?? "Guest"
print("Welcome, \(displayName)")

Nil Coalescing with Chained Fallbacks

?? can be chained so that if the first optional is nil, the second is tried, and so on, down to a final guaranteed default.

Example: Nil Coalescing with Chained Fallbacks

markup
let primary: String? = nil
let secondary: String? = nil
let fallback = "[email protected]"
let email = primary ?? secondary ?? fallback
print("Using email: \(email)")
Common Mistakes
  1. Using an if-else block just to provide a fallback default when ?? would express the same logic in one line.
  2. Forgetting that the right-hand side of ?? must match the optional's wrapped type (or be another optional of that type).
  3. Chaining ?? incorrectly assuming operator precedence works differently than left-to-right with the rest of an expression -- parentheses help clarify complex expressions.
Chapter Summary
  • a ?? b evaluates to a if it's non-nil, or b otherwise.
  • ?? provides a clean, single-line way to supply default values for optionals.
  • The fallback value on the right must be of the same (non-optional) type as the optional's wrapped value.
  • ?? can be chained: a ?? b ?? c tries each in turn.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.