viktor.radovic viktor.radovic - 1 year ago 147
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)


{ 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download