【问题标题】:swift syntax, check for nil before unwrapping [duplicate]快速语法,在展开之前检查 nil [重复]
【发布时间】:2016-11-03 15:13:05
【问题描述】:

我发现在展开之前检查nil 很长,有没有更短的方法?我是 Swift 新手,谢谢

     func loadSettings(defaults: UserDefaults) {
       if defaults.string(forKey: "driverId") != nil {
         driverId = defaults.string(forKey: "driverId")!

       }
     } 

【问题讨论】:

标签: swift swift3


【解决方案1】:

当然:

if let driverId = defaults.string(forKey: "driverId") {
    // use driverId
}

【讨论】:

    【解决方案2】:
     func loadSettings(defaults: UserDefaults) {
        if let driverId = defaults.string(forKey: "driverId"){
         // process driverId
        }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 2020-12-10
      相关资源
      最近更新 更多