Optional chaining
Optional chaining is a process to query and call properties, methods, and subscripts on an optional that may currently be nil
. Optional chaining in Swift is similar to messaging nil
in Objective-C but in a way that works for any type and can be checked for success or failure.
The following example presents two different classes. One of the classes, Person
, has a property of type of Optional (residence)
, which wraps the other class type Residence
:
class Residence { var numberOfRooms = 1 } class Person { var residence: Residence? }
We will create an instance of the Person
class, sangeeth
:
let residence = Residence() residence.numberOfRooms = 5 let sangeeth = Person() sangeeth.residence = residence
To check for numberOfRooms
, we need to use the residence
property of the Person
class, which is an optional
. Optional chaining enables us to go through Optionals
as follows:
if let roomCount = sangeeth.residence?.numberOfRooms { // Use the roomCount print...