因此在iOS
Swift中我们可以执行可选链接来简化零检查,就像在
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中可选链接的用法,但是我们怎么知道链实际在哪里断开(如果住所或地址是零).我们可以确定住所或地址是否为零,或者我们需要使用if-else再次检查?
那不要做链.如果你不打算停止,这条链只会很有趣.如果你这样做,请在有趣的地方进行分解 – 否则,你会在哪里输入不良案例的代码?
if let residence = john.residence { if let address = residence.address { ... } else { println("missing address") } } else { println("missing residence") }