【问题标题】:Is there a better way of coping with Swift's nested "if let" "pyramid of doom?"有没有更好的方法来应对 Swift 嵌套的“如果让”“厄运金字塔”?
【发布时间】: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


【解决方案1】:

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 )
}

【讨论】:

    【解决方案2】:

    在 Swift 2 中,我们有 guard 语句。

    代替:

    func myFunc(myOptional: Type?) {
      if let object = myOptional! {
        ...
      }
    }
    

    你可以这样做:

    func myFunc(myOptional: Type?) {
      guard array.first else { return }
    }
    

    检查来自 NSHipster 的 http://nshipster.com/guard-and-defer/。

    【讨论】:

      【解决方案3】:

      正如评论者所说,Swift 1.2 现在有multiple-let 语法:

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

      也就是说,在这种情况下,您似乎可以通过 1.1 中的可选链接来完成这一切,具体取决于您的对象是什么:

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

      注意,最好使用first(如果这是一个数组)而不是[0],以解决数组为空的可能性。并映射到 double 而不是 ! (如果该值不是双倍的话,它会爆炸)。

      【讨论】:

      • 感谢 Airspeed 速度。但是,您发布的代码 sn-p 在 'if' 条件之后抛出“Expected '{' after 'if' condition”。我可能在这里使用旧版本的 Swift 吗?我特别想避免可选链接,谢谢。 MJB。
      • 我明白了。我需要 XCode 6.3 测试版。我会跑过去搞定的,谢谢大家。
      • Airspeed Velocity:我注意到这些 let 都是弱类型的。这正常吗?我来自一种尽可能强类型化的文化,理想情况下是一切。这对 Swift 人群来说不那么重要了吗?
      • Swift 中的所有变量都是强类型的,但它们的类型可以“推断”。例如,如果你写let i = 1,那么i 将是Int,但你不需要显式地写i: Int——Swift 会从右边的类型中找出来。那么如果你写let j = i,j 也将是Int。但是如果你写let k = i + 1.5你会得到一个错误,“二元运算符'+'不能应用于'Int'和'Double'类型的操作数”
      • 这个想法是,显式类型通常很混乱,从上下文中可以明显看出,但会妨碍代码易于阅读和理解。
      猜你喜欢
      • 1970-01-01
      • 2019-02-19
      • 2013-08-04
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      • 2022-06-19
      • 1970-01-01
      相关资源
      最近更新 更多