Use Optional Chaining in Swift
Written by Team Kodeco
Optional chaining is a process for querying and calling properties, methods and subscripts on an optional that might currently be nil
. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil
, the property, method or subscript call returns nil
.
Multiple queries can be chained together and the entire chain fails gracefully if any link in the chain is nil
.
// Classes for testing
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
// Example 1: Create a person, with the residence nil
let john = Person()
if let roomCount = john.residence?.numberOfRooms {
print("John's residence has \(roomCount) room(s).")
} else {
print("Unable to retrieve the number of rooms.")
}
// Prints "Unable to retrieve the number of rooms."
// Example 2: Create a person, with the residence set
john.residence = Residence()
if let roomCount = john.residence?.numberOfRooms {
print("John's residence has \(roomCount) room(s).")
} else {
print("Unable to retrieve the number of rooms.")
}
// Prints "John's residence has 1 room(s)."
In the example above, the residence property of the john
object is nil
, so the call to numberOfRooms
returns nil
and the if-let statement’s condition is false.
Note: When using optional chaining, it’s important to keep in mind that the returned value will always be an optional, even if the property, method, or subscript you’re querying returns a non-optional value.
Set a Value if not Nil
You can also use optional chaining to set a property’s value if the optional isn’t nil
:
john.residence?.numberOfRooms = 5
if let roomCount = john.residence?.numberOfRooms {
print("John's residence has \(roomCount) room(s).")
} else {
print("Unable to retrieve the number of rooms.")
}
// Prints "John's residence has 5 room(s)."
In the example above, numberOfRooms
is only updated if residence
isn’t nil.