为什么可以在没有任何错误的情况下为非可选项分配非可选项?

时间:2016-12-22 20:46:38

标签: swift optional

我正在阅读Apple的Optional Chaining,我对它的含义感到有些困惑

class Person {
    var residence: Residence?
}

class Residence {
    var numberOfRooms = "fifty"
}

let john = Person()
john.residence = Residence()

let roomCountSafe = john.residence?.numberOfRooms // here numberOfRooms is no longer a String but instead is a String? right?

john.residence?.numberOfRooms = "thirty" // Line A: how can we assign a nonOptional to an Optional?

print(john.residence?.numberOfRooms)

var x = "aString"

但不能将可选项分配给nonOptional

x = john.residence?.numberOfRooms // Line B: error: value of optional type
 'String?' not unwrapped; did you mean to use '!' or '?'?

或者这是否解释了选项是'枚举'并且你要么进入'case'集合,要么就是我在A行做的事情。为什么A行返回一个可选的(“30”是因为它可能因为可选链接的性质而失败?

(我确实理解了lineB,但是当涉及到B行与A行时,我有点困惑)

0 个答案:

没有答案