Optional Chaining
Optional chaining lets you safely ask a chain of questions about something that might not exist, stopping quietly at the first "no" instead of crashing.
Chaining Through an Optional Property
Using ?. after an optional lets you safely access one of its properties, automatically returning nil if the optional itself is empty.
Example: Chaining Through an Optional Property
struct Address {
var city: String
}
struct Person {
var address: Address?
}
let person = Person(address: Address(city: "Paris"))
print(person.address?.city as Any)
let personNoAddress = Person(address: nil)
print(personNoAddress.address?.city as Any)
Login to try C/C++/Java/PHP code in the editor
Combining Chaining with Nil Coalescing
Optional chaining is often paired with ?? to supply a default value when any part of the chain is missing.
Example: Combining Chaining with Nil Coalescing
struct Address {
var city: String
}
struct Person {
var address: Address?
}
let person = Person(address: nil)
let city = person.address?.city ?? "Unknown city"
print(city)
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Confusing optional chaining's
?.with force-unwrapping's!-- chaining returnsnilgracefully instead of crashing on a missing link. - Forgetting that the overall result of an optional chain is always itself an optional, even if the final property isn't.
- Trying to chain through a method call that doesn't itself return an optional, and being surprised the whole expression's result is still optional because of an earlier link.
Chapter Summary
?.accesses a property or calls a method only if the optional isn'tnil.- If any link in the chain is
nil, the entire expression short-circuits tonil. - The overall result of a chain is always wrapped in an optional, regardless of the underlying property's type.
- Chaining avoids deeply nested
if letchecks for accessing nested optional structures.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: