Optional chaining lets you safely access properties or call methods on values that might be nil (empty). It helps avoid crashes by stopping if something is nil.
Optional chaining with ?. in Swift
class Person { var residence: Residence? } class Residence { var numberOfRooms = 1 } let john = Person() let roomCount = john.residence?.numberOfRooms
The ? after residence means: if residence is nil, stop and return nil instead of crashing.
Optional chaining returns an optional value, so roomCount is an Int? (optional Int).
residence is nil, so optional chaining stops and roomCount is nil.class Person { var residence: Residence? } class Residence { var numberOfRooms = 1 } let john = Person() // residence is nil, so this returns nil let roomCount = john.residence?.numberOfRooms print(roomCount) // prints nil
residence exists, so optional chaining accesses numberOfRooms and returns it wrapped in Optional.class Person { var residence: Residence? } class Residence { var numberOfRooms = 1 } let john = Person() john.residence = Residence() // residence is not nil, so this returns 1 let roomCount = john.residence?.numberOfRooms print(roomCount) // prints Optional(1)
class Person { var residence: Residence? } class Residence { var rooms: [String] = [] func printNumberOfRooms() { print("Number of rooms: \(rooms.count)") } } let john = Person() john.residence = Residence() // Call method safely with optional chaining john.residence?.printNumberOfRooms() // prints "Number of rooms: 0"
class Person { var residence: Residence? } class Residence { var rooms: [String] = [] func addRoom(name: String) { rooms.append(name) } } let john = Person() // This does nothing because residence is nil john.residence?.addRoom(name: "Living Room") // residence is still nil print(john.residence?.rooms.count) // prints nil
This program shows optional chaining stopping safely when residence is nil, then working after residence is set.
class Person { var residence: Residence? } class Residence { var rooms: [String] = [] func addRoom(name: String) { rooms.append(name) } func printNumberOfRooms() { print("Number of rooms: \(rooms.count)") } } // Create a person without a residence let john = Person() // Try to print number of rooms safely john.residence?.printNumberOfRooms() // Nothing prints because residence is nil // Add a residence john.residence = Residence() // Add rooms safely john.residence?.addRoom(name: "Living Room") john.residence?.addRoom(name: "Kitchen") // Print number of rooms again john.residence?.printNumberOfRooms()
Time complexity: Optional chaining itself is O(1) because it just checks for nil and accesses properties or calls methods.
Space complexity: No extra space is used beyond the objects themselves.
Common mistake: Forgetting that optional chaining returns an optional, so you might need to unwrap the result.
Use optional chaining when you want to safely access or call on optionals without many if-let checks. Use if-let if you want to unwrap and use the value immediately.
Optional chaining safely accesses properties or methods on optionals.
It stops and returns nil if any part is nil, avoiding crashes.
It returns an optional value, so you may need to unwrap it later.
Practice
?. operator do in Swift when used with optionals?Solution
Step 1: Understand optional chaining purpose
The?.operator is used to safely access properties or methods on an optional value.Step 2: Behavior when optional is nil
If the optional is nil, the chaining stops and returns nil instead of crashing.Final Answer:
It safely accesses a property or method and returns nil if the optional is nil. -> Option CQuick Check:
Optional chaining = safe access with nil return [OK]
- Confusing optional chaining with forced unwrapping
- Thinking it unwraps optionals automatically
- Assuming it provides default values
name property of an optional person object using optional chaining?Solution
Step 1: Identify correct optional chaining syntax
Optional chaining uses?.between the optional variable and the property.Step 2: Check each option
person?.name usesperson?.name, which is correct syntax. person!.name forces unwraps with!. person.name? places?incorrectly. person->name uses invalid operator.Final Answer:
person?.name -> Option DQuick Check:
Optional chaining syntax = variable?.property [OK]
- Using ! instead of ? for optional chaining
- Placing ? after the property name
- Using invalid operators like ->
class Person {
var pet: Pet?
}
class Pet {
var name: String
init(name: String) { self.name = name }
}
let person = Person()
let petName = person.pet?.name
print(petName)What will be printed?
Solution
Step 1: Analyze the optional chaining result
Sinceperson.petis nil (not assigned),person.pet?.namereturnsnilof typeString?.Step 2: Understand print output of optional nil
Printing an optional value that is nil in Swift showsOptional(nil)because the variable itself is an optional.Final Answer:
Optional(nil) -> Option AQuick Check:
print(String? nil) = Optional(nil) [OK]
- Thinking print shows nil
- Expecting empty string output
- Thinking it causes runtime error
struct Car {
var owner: Person?
}
let car = Car()
let ownerName = car.owner?.name!Solution
Step 1: Identify forced unwrap misuse
The code usescar.owner?.name!which tries to force unwrap the property without parentheses.Step 2: Correct syntax for forced unwrap after optional chaining
Forced unwrap must be applied to the entire optional chaining expression with parentheses like(car.owner?.name)!.Final Answer:
Using forced unwrap (!) after optional chaining without parentheses -> Option AQuick Check:
Force unwrap after optional chaining needs parentheses [OK]
- Forgetting parentheses around optional chain before !
- Assuming optional chaining can be forced unwrapped directly
- Ignoring compiler error details
class Address {
var city: String?
}
class User {
var address: Address?
}
let user = User()Which code safely prints the city name if it exists, or "Unknown" if city or address is nil?
Solution
Step 1: Understand optional chaining with nil coalescing
Usinguser.address?.citysafely accesses city, returning nil if address or city is nil.Step 2: Use nil coalescing operator to provide default
The?? "Unknown"provides "Unknown" if the optional is nil, avoiding crashes.Final Answer:
print(user.address?.city ?? "Unknown") -> Option BQuick Check:
Optional chaining + ?? = safe access with default [OK]
- Forcing unwraps causing runtime crashes
- Not handling nil for nested optionals
- Using optional chaining without default fallback
Ready to prove it?
Pass the test and this pattern moves unknown
