Swift 问题 2 错误处理
Issue with Swift 2 Error Handling
我正在使用 REST 获取 JSON 数据,然后对其进行解析。为此,我使用 NSJSONObjectWithData,据我所知,此方法过去在其参数中有一个错误处理程序,但现在已不存在。在我的代码中:
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.
}
我正在使用 REST 获取 JSON 数据,然后对其进行解析。为此,我使用 NSJSONObjectWithData,据我所知,此方法过去在其参数中有一个错误处理程序,但现在已不存在。在我的代码中:
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.
}