點擊查看源碼
//可選鏈
func test() {
class Person {
//可選屬性可能為nil或Residence類
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
let john = Person()
john.residence = Residence()
//可選獲得
var roomCount = john.residence?.numberOfRooms
print(roomCount)
//強制獲得
roomCount = john.residence!.numberOfRooms
print(roomCount)
// if獲得
if let roomCount = john.residence?.numberOfRooms {
print(roomCount)
}
/* print
Optional(1)
Optional(1)
1
*/
}