我正在观看Apple的所有快速教程,但我遇到了其中一个例子的问题:
class Person {
var residence: Residence?
}
class Residence {
var address: Address?
}
class Address {
var buildingNumber: String? = "234"
var streetName: String? = "Main St."
var appartmentNumber: String?
}
let paul = Person()
var addressNumber: Int?
addressNumber = paul.residence?.address?.buildingNumber?.toInt()
if let number = addressNumber {
"correct"
} else {
"fault"
}
它总是打印出来"故障"。我有什么痛苦明显的遗失吗?
答案 0 :(得分:2)
let paul = Person()
您对paul
不做任何其他事情,包括设置其可选的居住变量。因此,在下一行代码中,您访问paul
的{{1}}住所。
nil
因此,使用可选链接,整个表达式返回addressNumber = paul.residence?.address?.buildingNumber?.toInt()
^ failing right here, residence? returns nil
,因此在下一个nil
语句中进行比较时,它是错误的。这就是执行if let
子句的原因。
答案 1 :(得分:2)
一次一步地思考。特别是,您的可选链接:
addressNumber = paul.residence?.address?.buildingNumber?.toInt()
问问自己:
什么是paul
?
paul
的{{1}}属性设置为什么?
residence
address
paul
的{{1}}是什么?
提示:你不应该超越第2步。
答案 2 :(得分:2)
如果您将代码更改为:
,那么您实际上永远不会创建有效的Residence
或Address
class Person {
// actually create a residence object
var residence: Residence? = Residence()
}
class Residence {
// actually create a address object
var address: Address? = Address()
}
class Address {
// ...
}
let paul = Person()
var addressNumber: Int?
// Before Paul was never assigned a valid residence, now one will be created
addressNumber = paul.residence?.address?.buildingNumber?.toInt()
if let number = addressNumber {
"correct"
} else {
"fault"
}
// gives you `correct`
然后它应该工作得很好!
答案 3 :(得分:1)
您永远不会初始化Person()
以外的任何内容,因此residence
上的paul
属性为nil
。
因此,在以下可选链中:
addressNumber = paul.residence?.address?.buildingNumber?.toInt()
^ you get nil here and don't continue
这意味着addressNumber
为nil
。