有没有更好的方法来应对斯威夫特的嵌套"如果让""厄运的金字塔?"

Jos*_*Mum 5 xcode if-statement let optional swift

有没有比嵌套if语句更好的处理可选属性链的方法?我被建议在检查可选属性时使用if,这有意义,因为它在编译时而不是运行时处理它们,但它看起来像是疯狂!有更好的方法吗?

以下是我最终得到的"厄运金字塔",例如:

( 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 )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

后记

Airspeed Velocity的答案是正确的答案,但是你需要使用Swift 1.2来使用逗号分隔的多个let,因为他建议,目前只在测试版的XCode 6.3中运行.

Air*_*ity 19

正如评论者所说,Swift 1.2现在具有多重语法:

if let jsonValue = users?.first,
       json = jsonValue.object,
       userIDValue = json[ "id" ],
       doubleID = userIDValue.double,
       userID = doubleID.map({ String(Int(doubleID))})
{
    println( userID )
}
Run Code Online (Sandbox Code Playgroud)

也就是说,在这种情况下,看起来您可以通过1.1中的可选链接来完成所有操作,具体取决于您的对象:

if let userID = users?.first?.object?["id"]?.double.map({String(Int($0))}) {

    println(userID)

}
Run Code Online (Sandbox Code Playgroud)

注意,使用更好first(如果这是一个数组)而不是[0],考虑到数组为空的可能性.并映射double而不是!(如果值不是双倍的话会爆炸).


Sha*_*y D 5

Swift-3 的更新:语法已更改:

if let jsonValue = users?.first,
       let json = jsonValue.object,
       let userIDValue = json[ "id" ],
       let doubleID = userIDValue.double,
       let userID = doubleID.map({ String(Int(doubleID))})
{
    println( userID )
}
Run Code Online (Sandbox Code Playgroud)