TibiaZ
TibiaZ

Reputation: 750

Errors thrown from here are not handled

I've got this problem trying to parse a JSON on my iOS app:

Relevant code:

let jsonData:NSDictionary = try JSONSerialization.jsonObject(with: urlData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers ) as! NSDictionary

/* XCode error ^^^ Errors thrown from here are not handled */

Could anybody help me ?

Upvotes: 47

Views: 58488

Answers (1)

shallowThought
shallowThought

Reputation: 19602

A possibly thrown error in let jsonData = try JSONSerialization ... is not handled.

You can ignore a possible error, and crash as penalty if an error occurs:

let jsonData = try! JSONSerialization ...

or return an Optional, so jsonData is nil in error case:

let jsonData = try? JSONSerialization ...

or you can catch and handle the thrown error:

do {
    let jsonData = try JSONSerialization ...
    //all fine with jsonData here
} catch {
    //handle error
    print(error)
}

You might want to study The Swift Language

Upvotes: 125

Related Questions