【问题标题】:Swift 2 jSON Call can throw but it is not marked with trySwift 2 jSON Call 可以抛出,但没有用 try 标记
【发布时间】:2015-06-24 09:36:05
【问题描述】:

昨天我更新到 El Capitan beta 2 和 Xcode 7 - beta 是强制性的。所以我将我的应用程序更新为 Swift 2 并且 json 字符串出现了新错误。这是我的代码:

let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary

这是错误:Call can throw , but it is not marked with 'try' and the error is not handled

【问题讨论】:

    标签: ios json xcode7 swift2


    【解决方案1】:

    您需要将其包装在 do/catch 块中,因为这是报告错误的首选方式,而不是使用 NSError

    do {
       let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
       // use jsonData
    } catch {
        // report error
    }
    

    【讨论】:

    • 感谢您的回复,无论如何这并不能解决问题:\
    • 我用 let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary 改变了,它可以工作
    • @Droppy 我知道我们不能强制解包因为JSONObjectWithData 必须throw 一些东西。但是,如果我们使用try!,那么出于学习目的,如果它失败了,那会不会只是展开并抛出并崩溃——就像强制展开一样?我的意思是在这种情况下try! 有什么功能优势吗?我问这个是因为如果我不得不强制崩溃,我可以选择强制解包或try!——似乎没有额外的好处
    【解决方案2】:

    输入“尝试!”在等号之后。

    let jsonData:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
    

    那么就不需要 catch 子句或 throws 声明了。如果您无法真正从那里的失败中恢复过来,那么这样做将是一个好主意。

    欲了解更多信息,请参阅:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html

    【讨论】:

      【解决方案3】:
      var UserDict = NSJSONSerialization.JSONObjectWithData(responseData, options:nil, error: &error) as? NSDictionary
      println("== \(UserDict)")
      

      【讨论】:

        猜你喜欢
        • 2016-01-24
        • 1970-01-01
        • 2015-08-24
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 2016-01-02
        相关资源
        最近更新 更多