Errors thrown from here are not handled

37,830

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

Share:
37,830
TibiaZ
Author by

TibiaZ

I am an iOS developer with excellent teamwork skills and a deep understanding on Cocoa Touch and iOS Design Patterns. I have great willingness to learn new things. Pragmatic problem solver, proactive and highly motivated. My professional target is to work surrounded by a creative and open-minded team.

Updated on March 08, 2020

Comments

  • TibiaZ
    TibiaZ about 4 years

    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 ?

  • Randika Vishman
    Randika Vishman almost 7 years
    You deserved an up vote! I'm new to Swift! Oh man, Swift is a pain in the ass at first! <3
  • gnasher729
    gnasher729 over 4 years
    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.