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.
Syntax
let result = object.optionalProperty?.member
let result = object.optionalProperty?.member ?? defaultValue
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
// Define a struct `Address`
struct Address {
var city: String
}
// Define a struct `Person`
struct Person {
var address: Address?
}
// Declare a constant `person`, set to `Person(address: Address(city: "Paris"))`
let person = Person(address: Address(city: "Paris"))
// Print `person.address?.city as Any` to the console
print(person.address?.city as Any)
// Declare a constant `personNoAddress`, set to `Person(address: nil)`
let personNoAddress = Person(address: nil)
// Print `personNoAddress.address?.city as Any` to the console
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
// Define a struct `Address`
struct Address {
var city: String
}
// Define a struct `Person`
struct Person {
var address: Address?
}
// Declare a constant `person`, set to `Person(address: nil)`
let person = Person(address: nil)
// Declare a constant `city`, set to `person.address?.city ?? "Unknown city"`
let city = person.address?.city ?? "Unknown city"
// Print `city` to the console
print(city)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: