【发布时间】:2014-06-17 19:03:27
【问题描述】:
Apple 提供了一个简洁的可选链示例
class Person {
var residence: Residence?
}
class Residence {
var numberOfRooms = 1
}
let john = Person()
if let roomCount = john.residence?.numberOfRooms {
println("John's residence has \(roomCount) room(s).")
} else {
println("Unable to retrieve the number of rooms.")
}
想象一下尝试通过一些算术运算来调整条件。这会导致编译器错误,因为模运算符不支持可选项。
if john.residence?.numberOfRooms % 2 == 0 {
// compiler error: Value of optional type Int? not unwrapped
println("John has an even number of rooms")
} else {
println("John has an odd number of rooms")
}
当然,您总是可以执行以下操作,但它缺乏可选链接的简单性和简洁性。
if let residence = john.residence {
if residence.numberOfRooms % 2 == 0 {
println("John has an even number of rooms")
}else{
println("John has an odd number of rooms")
}
} else {
println("John has an odd number of rooms")
}
是否有任何 Swift 语言功能可以提供更好的解决方案?
【问题讨论】:
标签: ios swift chaining optional