Leo Starić Leo Starić - 2 years ago 215
Swift Question

Cannot properly convert value from JSON dictionary

I'm stuck on a weird problem.
I'm parsing a JSON response via Alamofire, and want to fetch a variable that just keeps throwing errors regardless whether I cast it to a String or Number, whilisting changing the error message every time I do :/
If I cast it to a String like this:

let kolicina = jsonCategory["kolicina"] as! String

if Int(kolicina) > 0 {

I get the error:

"Could not cast value of type '__NSCFNumber' (0x10f051368) to 'NSString' (0x10e627b48)."

When I try to cast it to a NSNumber:

let kolicina = jsonCategory["kolicina"] as! NSNumber

if kolicina.integerValue > 0 {

I get:

"Could not cast value of type 'NSTaggedPointerString' (0x10effcae8) to 'NSNumber' (0x10e5d32a0)."

This is what I get for that specific variable when I print the Dictionary:

kolicina = 0;

Can someone point me in the right direction?

Answer Source

It seems you have a combination of strings and integers in there. I would recommend you to fix the JSON and keep the data either as a string or a number, not both.

If you want to parse such a format, you will have to try to parse it as a NSNumber or as a NSString, e.g.:

let kolicina = jsonCategory["kolicina"]

if let kolicinaString = kolicina as? String {
} else if let kolicinaInt = kolicina as? Int {

with the > 0 checks you could do something like this:

if let kolicinaString = kolicina as? String,
       kolicinaInt = Int(kolicinaString) where kolicinaInt > 0 {

    print("String: \(kolicinaInt)")
} else if let kolicinaInt = kolicina as? Int where kolicinaInt > 0 {

    print("Int: \(kolicinaInt)")

or using a ternary operator:

let kolicinaInt = (kolicina is String) ? Int(kolicina as! String) : kolicina as? Int

if kolicinaInt > 0 {
    print("Kolicina: \(kolicinaInt)")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download