//可选链测试 class Person{ var residence:Residence! var name:String init(name:String){ self.name = name } } ///住宅 class Residence { var residenceNum = 101 } var lucy = Person(name: "Lucy") //没有为lucy初始化住宅 if let roomNumber1 = lucy.residence?.residenceNum { print("(lucy.name)有住宅,住宅号是(roomNumber1)") }else{ print("(lucy.name)没有住宅") } var lily = Person(name: "Lily") lily.residence = Residence() if let roomNumber2 = lily.residence?.residenceNum { print("(lily.name)有住宅,住宅号是(roomNumber2)") }else{ print("(lily.name)没有住宅") }
//1.可选链的访问方式:将强制解析的感叹号换成?,在隐式解析的后面也添加?后缀
//2.可选链会自动判断程序访问的关联实例是否为nil