Swift 2 jSON调用可以抛出但是没有标记为try

mar*_*tus 18 json ios xcode7 swift2

昨天我更新到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

Dro*_*ppy 37

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

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

  • 我改变了让`jsonData =尝试NSJSONSerialization.JSONObjectWithData(urlData!,options:NSJSONReadingOptions.MutableContainers)!NSDictionary`并且它的工作原理 (5认同)