Swift 2错误处理问题 [英] Issue with Swift 2 Error Handling

查看:97
本文介绍了Swift 2错误处理问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用REST获取JSON数据,然后解析它。为此我使用NSJSONObjectWithData,据我所知,这个方法曾经在其参数中有一个错误处理程序,但它不再存在。在我的代码中:

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;

我收到一条错误消息:

呼叫可以抛出,但没有标记'尝试'并且错误未得到处理

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

我将如何修复此错误?

推荐答案

这是正确的实现,

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.
}

这篇关于Swift 2错误处理问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆