我有下面的代码,它工作正常,但我预计该行print(john.residence!.numberOfRooms)
会崩溃,因为我的numberOfRooms
变量具有nil
值,并且在将其值作为参数传递给print()
. 谁能解释一下为什么这不会触发运行时错误并nil
安全打印?
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms: Int?
}
let john = Person()
john.residence = Residence()
print(john.residence!.numberOfRooms)