Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Optional instances

Both struct and class objects may be declared as optionals, as follows:

let secondDriver: Driver? = Driver(name: "Fred", 
yearOfBirth: 1904)

An optional instance's properties can be assigned to an optional variable as follows:

var nameOnSchedule:String? 
nameOnSchedule = secondDriver?.name

Note that, by making nameOnSchedule an optional, we can assign it to be the name of secondDriver, if there is one, or nil if there is not, without having to test explicitly.