Issue with Swift 2 Error Handling

爷,独闯天下 提交于 2019-12-30 10:04:27

问题


I am using REST to get JSON data and then parse it. To do this I am using NSJSONObjectWithData, as far as I'm aware this method used to have an error handler within its parameters but it's no longer there. In my code here:

let err: NSError?
let options:NSJSONReadingOptions = NSJSONReadingOptions.MutableContainers
var jsonResult = NSJSONSerialization.JSONObjectWithData(data!, options: options) as! NSDictionary;

I get an error which says:

"Call can throw, but it is not marked with 'try' and the error is not handled"

How would I go about fixing this error?


回答1:


Here is the correct implementation,

do {
    let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

    //Use your dictionary here.
    print("JSON : \(jsonDictionary)")
}
catch  {
    print(error)
    //Handle any error.
}


来源:https://stackoverflow.com/questions/31051263/issue-with-swift-2-error-handling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!