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(roomCount)
}

The roomCount variable will be five, as expected.

This can be used to call methods and subscripts through optional chaining.

We can add force unwrapping to any chain items by replacing the question mark with an exclamation mark as follows:

let roomCount = sangeeth.residence!.numberOfRooms

Again, we need to be cautious when we use force unwrapping in optional chains.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset