Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct handling of NSJSONSerialization (try catch) in Swift (2.0)?

Tags:

ios

swift

arowmy init works fine in Swift < 2 but in Swift 2 I get a error message from Xcode Call can throw, but it is not marked with 'try' and the error is not handled at let anyObj = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]. I think in my case I can´t use a try catch block because super is not initialized at this time. "Try" need a function that throws.

here is my function:

required init(coder aDecoder : NSCoder) {     self.name  = String(stringInterpolationSegment: aDecoder.decodeObjectForKey("name") as! String!)     self.number = Int(aDecoder.decodeIntegerForKey("number"))     self.img = String(stringInterpolationSegment: aDecoder.decodeObjectForKey("image") as! String!)     self.fieldproperties = []      var tmpArray = [String]()     tmpArray = aDecoder.decodeObjectForKey("properties") as! [String]       let c : Int = tmpArray.count     for var i = 0; i < c; i++     {         let data : NSData = tmpArray[i].dataUsingEncoding(NSUTF8StringEncoding)!           // Xcode(7) give me error: 'CAll can thorw, but it is not marked with 'try' and the error is not handled'         let anyObj =  NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]          let label = anyObj["label"] as AnyObject! as! String         let value = anyObj["value"] as AnyObject! as! Int         let uprate = anyObj["uprate"] as AnyObject! as! Int         let sufix = anyObj["sufix"] as AnyObject! as! String          let props = Fieldpropertie(label: label, value: value, uprate: uprate, sufix: sufix)         self.fieldproperties.append(props)     } } 

Xcode mean that: let anyObj = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]

but I have no idea to do here the right think according to this document https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html

like image 273
Mirko Brunner Avatar asked Jul 08 '15 15:07

Mirko Brunner


People also ask

How do you handle try catch in Swift?

The try/catch syntax was added in Swift 2.0 to make exception handling clearer and safer. It's made up of three parts: do starts a block of code that might fail, catch is where execution gets transferred if any errors occur, and any function calls that might fail need to be called using try .

What is try try try in Swift?

More dangerous is the use of try! . In Swift, an exclamation mark always serves as a warning sign. By appending an exclamation mark to the try keyword, error propagation is disabled. This means that, if an error does get thrown, your application crashes as the result of a runtime error.

Do try catch throw Swift?

Try catch in Swift combined with throwing errors make it possible to nicely handle any failures in your code. A method can be defined as throwing which basically means that if anything goes wrong, it can throw an error.


1 Answers

The jsonObject can throw errors, so put it within do block, use try, and catch any errors thrown. In Swift 3:

do {     let anyObj = try JSONSerialization.jsonObject(with: data) as! [String: Any]      let label = anyObj["label"] as! String     let value = anyObj["value"] as! Int     let uprate = anyObj["uprate"] as! Int     let sufix = anyObj["sufix"] as! String      let props = Fieldpropertie(label: label, value: value, uprate: uprate, sufix: sufix)      // etc. } catch {     print("json error: \(error.localizedDescription)") } 

Or, in Swift 4, you can simplify your code by making your struct conform to Codable:

struct Fieldpropertie: Codable {     let label: String     let value: Int     let uprate: Int     let suffix: String } 

Then

do {     let props = try JSONDecoder().decode(Fieldpropertie.self, from: data)     // use props here; no manual parsing the properties is needed } catch {     print("json error: \(error.localizedDescription)") } 

For Swift 2, see previous revision of this answer.

like image 140
Rob Avatar answered Sep 26 '22 19:09

Rob