markutus
markutus

Reputation: 603

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

Upvotes: 18

Views: 12977

Answers (3)

Jerry Frost
Jerry Frost

Reputation: 467

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

Upvotes: 2

Droppy
Droppy

Reputation: 9721

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
}

Upvotes: 37

Kirit Modi
Kirit Modi

Reputation: 23407

var UserDict = NSJSONSerialization.JSONObjectWithData(responseData, options:nil, error: &error) as? NSDictionary
println("== \(UserDict)")

Upvotes: 0

Related Questions