viktor.radovic viktor.radovic - 27 days ago 22
iOS Question

Swift parse JSON with variable types

I have JSON data serialized as NSDictionary type, for instance

{ data = 0; } // "data":"0" (when I see its value in debugger)


or

{ data = 1; } //"data": Int64(1)(when I see its value in debugger)


I m trying to access this data as:

json["data"] as! Int


, but sometimes it cannot be parsed as Integer, because if its 0 it has String value, and I get error:

Could not cast value of type 'NSTaggedPointerString' (0x109b54b90) to 'NSNumber'


What is wrong, and how can I solve this?

Answer

Conditionals to the rescue!

let data: Int = json["data"] as? Int ?? 0

If the the value for the "data" key is missing or "0" the data it will be set to zero.

Comments