【发布时间】:2015-06-04 13:42:06
【问题描述】:
有没有比嵌套 if let 语句更好的方法来处理一系列可选属性?有人建议我在检查可选属性时使用 if let ,这是有道理的,因为它在编译时而不是运行时处理它们,但它看起来非常疯狂!有没有更好的办法?
以下是我最终得到的当前“末日金字塔”,例如:
( users: [ JSONValue ]? ) in
if let jsonValue: JSONValue = users?[ 0 ]
{
if let json: Dictionary< String, JSONValue > = jsonValue.object
{
if let userIDValue: JSONValue = json[ "id" ]
{
let userID: String = String( Int( userIDValue.double! ) )
println( userID )
}
}
}
后记
Airspeed Velocity 下面的答案是正确的答案,但您将需要 Swift 1.2 使用多个用逗号分隔的 let,正如他所建议的那样,目前仅在 XCode 6.3 中运行,该版本处于测试阶段。
【问题讨论】:
-
这就是臭名昭著的“末日金字塔”问题,最终在 Swift 1.2 中以一种优雅的方式解决了。你可以阅读more about it here
标签: xcode swift if-statement optional let