45

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 ?

TibiaZ
  • 730
  • 1
  • 8
  • 21

1 Answers1

119

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

shallowThought
  • 19,212
  • 9
  • 65
  • 112
  • 4
    You deserved an up vote! I'm new to Swift! Oh man, Swift is a pain in the ass at first! <3 – Randika Vishman Jun 08 '17 at 21:11
  • 1
    Another possibility: Inside a throwing function f, you can call another throwing function g without using "try". If g throws an error, f returns immediately and throws the same error. – gnasher729 Jan 13 '20 at 22:47