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

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

markup
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)

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

markup
struct Address {
    var city: String
}
struct Person {
    var address: Address?
}
let person = Person(address: nil)
let city = person.address?.city ?? "Unknown city"
print(city)
Common Mistakes
  1. Confusing optional chaining's ?. with force-unwrapping's ! -- chaining returns nil gracefully instead of crashing on a missing link.
  2. Forgetting that the overall result of an optional chain is always itself an optional, even if the final property isn't.
  3. 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't nil.
  • If any link in the chain is nil, the entire expression short-circuits to nil.
  • The overall result of a chain is always wrapped in an optional, regardless of the underlying property's type.
  • Chaining avoids deeply nested if let checks for accessing nested optional structures.
🔒

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.