Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2 jSON Call can throw but it is not marked with try

yesterday i updated to El Capitan beta 2 and Xcode 7 - beta is mandatory. So i updated my app to Swift 2 and new error comes to the json string. This is my code :

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

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

like image 634
markutus Avatar asked Jun 24 '15 09:06

markutus


2 Answers

You need to wrap it in a do/catch block as this is the preferred way of reporting errors, rather than using NSError:

do {
   let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
   // use jsonData
} catch {
    // report error
}
like image 143
Droppy Avatar answered Sep 28 '22 11:09

Droppy


Put the term "try!" after the equals sign.

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

No need then, for the catch clause, or for a throws declaration. Doing so would be a good idea if you cannot truly recover from a failure there.

For more information, see: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html

like image 28
Jerry Frost Avatar answered Sep 28 '22 09:09

Jerry Frost