Problem with Swift 2 Error Handling

I use REST to get JSON data and then parse it. For this I use NSJSONObjectWithData, as far as I know, this method was used to handle errors in its parameters, but it no longer exists. In my code here:

let err: NSError?
let options:NSJSONReadingOptions = NSJSONReadingOptions.MutableContainers
var jsonResult = NSJSONSerialization.JSONObjectWithData(data!, options: options) as! NSDictionary;

I get an error message:

"The call may cause, but it is not marked" try ", and the error is not processed"

How can I fix this error?

+4
source share
1 answer

Here is the correct implementation,

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.
}
+3
source

All Articles