April 2026
Intermediate
683 pages
25h 29m
English
Optional chaining in Swift is an extended version of optional binding, which lets you access the properties of an optional in case it is not nil.
Inspect Listing 6.16 for a demonstration, where getEmptyRooms() returns an optional array of strings. This is actually an array of empty rooms in a hotel. If all rooms are booked, then the function will return nil.
// Functionfunc getEmptyRooms() -> [String]? { return nil // Simulation}// Main flowif let emptyRoom = getEmptyRooms()?[0] { print("Empty room: \(emptyRoom)")} else { print("No empty rooms, sorry")}
Listing 6.16 Optional Chaining with nil Value
In the main flow, an extended optional binding syntax is present: if let emptyRoom = getEmptyRooms()?[0]. If getEmptyRooms() ...
Read now
Unlock full access