如何知道可选链接在哪里中断? [英] How to know where Optional Chaining is breaking?
问题描述
So in iOS Swift we can do optional chaining to simplify the nil
checking like in the official documentation
let johnsAddress = Address()
johnsAddress.buildingName = "The Larches"
johnsAddress.street = "Laurel Street"
john.residence!.address = johnsAddress
if let johnsStreet = john.residence?.address?.street {
println("John's street name is \(johnsStreet).")
} else {
println("Unable to retrieve the address.")
}
// prints "John's street name is Laurel Street."
我了解john.residence?.address?.street
中可选链的用法,但是我们怎么知道链在哪里断开(如果residence
或address
是nil
).是否可以确定residence
或address
是nil
,还是需要再次使用if-else
进行检查?
I understand about the usage of the optional chaining in john.residence?.address?.street
but how can we know where is actually the chain is breaking (if either residence
or address
is nil
). Can we determine if residence
or address
is nil
, or we need to check it again with if-else
?
推荐答案
然后不要进行链接.仅当您不想停止时,链条才会有趣.如果这样做的话,请在有趣的地方将其分解-否则,您将在哪里放置坏情况代码?
Don't do the chain then. The chain is only interesting if you don't intend to stop. If you do, break it up at interesting spots - otherwise, where would you put in the code for the bad cases?
if let residence = john.residence {
if let address = residence.address {
...
} else {
println("missing address")
}
} else {
println("missing residence")
}
这篇关于如何知道可选链接在哪里中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!