有没有更好的方法来应对Swift的嵌套"if let"问题. “厄运金字塔?" [英] Is there a better way of coping with Swift's nested "if let" "pyramid of doom?"

查看:127
本文介绍了有没有更好的方法来应对Swift的嵌套"if let"问题. “厄运金字塔?"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a better way of dealing with a chain of optional properties than nested if let statements? I have been advised to use if lets when examining optional properties, which makes sense as it deals with them at compile time rather than run time, but it looks like utter madness! Is there is a better way?

这是我最后遇到的当前厄运金字塔",例如:

Here is the current "pyramid of doom" I have ended up with, as an example:

( 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,如他所建议的那样,当前仅在Beta的XCode 6.3中运行.

Airspeed Velocity's answer below is the right answer, but you will need Swift 1.2 to use multiple lets separated by commas as he suggests, which only currently runs in XCode 6.3, which is in beta.

推荐答案

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

As commenters have said, Swift 1.2 now has multiple-let syntax:

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

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

That said, in this instance it looks like you could might be able to do it all via optional chaining in 1.1, depending on what your objects are:

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

    println(userID)

}

请注意,考虑到数组为空的可能性,最好使用first(如果这是一个数组)而不是[0].然后在double而不是!上进行映射(如果该值不可双倍,则将爆炸).

Note, much better to use first (if this is an array) rather than [0], to account for the possibility the array is empty. And map on the double rather than ! (which would blow up if the value is not double-able).

这篇关于有没有更好的方法来应对Swift的嵌套"if let"问题. “厄运金字塔?"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆