100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Swift

Nil Coalescing Operator in Swift

The `??` operator supplies a default value when an optional is nil, in a single concise expression.

OptionalsBeginner7 min readJul 8, 2026
Analogies

Introduction

Often you just want to use an optional's value if it exists, and fall back to some default otherwise. Writing a full if let ... else block for this every time is verbose. The nil coalescing operator ?? compresses that pattern into a single expression: it returns the optional's unwrapped value if it is non-nil, or a default value you supply if it is nil.

🏏

Cricket analogy: Instead of writing a full over of if-else commentary to decide a fallback batting order, ?? is like a captain who instantly slots in the reserve opener if the regular one is unavailable, collapsing the whole decision into one quick substitution.

Syntax

swift
let value = optionalValue ?? defaultValue

Explanation

optionalValue ?? defaultValue is shorthand for: 'if optionalValue contains a value, unwrap and use it; otherwise, use defaultValue.' The type of defaultValue must match the wrapped type of optionalValue (a non-optional type), and the result of the whole expression is always non-optional. This is exactly equivalent to writing optionalValue != nil ? optionalValue! : defaultValue, but far safer and more readable since it avoids force unwrapping entirely. You can also chain multiple ?? operators to fall through several optionals in sequence.

🏏

Cricket analogy: selectedOpener ?? reserveOpener unwraps the chosen opener if picked, otherwise slots in the reserve, exactly equivalent to selectedOpener != nil ? selectedOpener! : reserveOpener but without risking a crash from force-unwrapping a batsman who never turned up; you can even chain ?? thirdChoice for a deeper bench.

Example

swift
var storedName: String? = nil
var displayName: String? = "Guest"

let greetingName = storedName ?? displayName ?? "Anonymous"
print("Welcome, \(greetingName)!")

var customTimeout: Int? = 30
let timeout = customTimeout ?? 60
print("Timeout: \(timeout)")

Output

swift
Welcome, Guest!
Timeout: 30

Key Takeaways

  • optionalValue ?? defaultValue returns the unwrapped value if present, otherwise the default.
  • The result of a ?? expression is always a non-optional type.
  • It is shorthand for an if-let/else pattern, without needing force unwrapping.
  • Multiple ?? operators can be chained to try several fallbacks in order.
  • The default value's type must match the optional's wrapped type.

Practice what you learned

Was this page helpful?

Topics covered

#Swift#SwiftProgrammingStudyNotes#Programming#NilCoalescingOperatorInSwift#Nil#Coalescing#Operator#Syntax#StudyNotes#SkillVeris