快速的选择

时间:2014-06-09 19:22:46

标签: swift ios8

我正在观看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"
}

它总是打印出来"故障"。我有什么痛苦明显的遗失吗?

4 个答案:

答案 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()

问问自己:

  1. 什么是paul

  2. paul的{​​{1}}属性设置为什么?

  3. residence address paul的{​​{1}}是什么?

  4. 提示:你不应该超越第2步。

答案 2 :(得分:2)

如果您将代码更改为:

,那么您实际上永远不会创建有效的ResidenceAddress
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

这意味着addressNumbernil