【问题标题】:Best way to unwrap optional type [duplicate]展开可选类型的最佳方法[重复]
【发布时间】:2016-07-14 04:40:54
【问题描述】:

我有情况

let a: Int? = getFromSomewhere()
if a == nil {
    return
}
let b = a!

我不喜欢太多层。但我认为这并不优雅。 你有更优雅的方式吗?

【问题讨论】:

  • “优雅”到底是什么意思? — 如果a 不是 nil,你为什么要返回?如果它 nil,你为什么要强制解开a?你的代码没有意义。如果你运行该代码,你会崩溃。
  • 我的错,应该是相等的。

标签: swift


【解决方案1】:

省略a,省略nil检查,省略force-unwrap;一行:

guard let b = getFromSomewhere() else {return}

【讨论】:

    【解决方案2】:

    您也可以使用guardif let 来解开选项:

    所以而不是:

    if a != nil {
        return
    }
    let b = a! 
    
    if let a = getFromSomewhere() { 
     // Do what you want with a
    } else {
      // a is nil
    }
    

    并带有保护声明:

    guard let a = getFromSomewhere() else {
        NSLog("error a is nil")
        return 
    } 
    
    // You can use a now if it's not nil
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 2020-02-28
      相关资源
      最近更新 更多