Optional binding allows us to unwrap one optional at a time, but what would happen if we had optional types embedded within other optional types? This would force us to have optional binding statements embedded within other optional binding statements. There is a better way to handle this by using optional chaining. Before we look at optional chaining, let's see how this would work with optional binding:
class Collar { var color: String init(color: String) { self.color = color } } class Pet { var name: String var collar: Collar? init(name: String) { self.name = name } } class Person { var name: String var pet: Pet? init(name: String) { self.name = name } }
In this example, we begin by defining a Collar
class, which has one property defined. This property is named color
, which...