【问题标题】:crash when objectForKey("Id") Id is not there?当 objectForKey("Id") Id 不存在时崩溃?
【发布时间】:2017-04-30 20:30:02
【问题描述】:

我在我的 iOS 应用程序中使用 alamofire 处理 http 请求。当我在响应中访问一个值时,如果键不存在或获取空值时,它会崩溃。

  var id = (response.result.value?[p-1].objectForKey("Id"))! as? Int

一般来说,我们如何检查 Swift 中不存在的值?

【问题讨论】:

    标签: ios swift dictionary null alamofire


    【解决方案1】:

    您必须在不强制的情况下解开您的选项。在您的情况下,您还应该考虑检查 response.result.value 是否至少有 p-1 元素:

    if let value = response.result.value
    {
       if p-1 < value.count
       {
           if let id = value[p-1].objectForKey("Id") as? Int
           {
               // Do whatever you want with id
           }
       }
    }
    

    你也可以使用guard 声明,我个人觉得更清楚:

    guard let value = response.result.value
       else { return }
    guard p-1 < value.count
       else { return }
    guard let id = value[p-1].objectForKey("Id") as? Int
       else { return }
    
    // Do whatever you want with id
    

    【讨论】:

    • 您没有尽可能地使用可选链接,请查看@ArnaudWurmel 的答案作为示例。
    • 我知道,我分解了可选链,让 OP 更清楚。
    【解决方案2】:

    你应该试试这个

    if let id = (response.result.value?[p-1].objectForKey("Id"))? as? Int {
       // some stuff
    }
    

    您的应用程序正在崩溃,因为您解开了 nil 对象:.objectForKey("Id")

    【讨论】:

    • 设为if let id = response.result.value?[p-1].objectForKey("Id") as? Int,这是最好的答案。
    • 你说得对@overactor,我贴他的代码,括号没用
    猜你喜欢
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 2013-07-01
    • 2019-09-02
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多