Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableDictionary treats NSString value as NSNumber

I have the following value in a NSMutableDictionary - see image

enter image description here

I'm attempting to get at "a" thus:

let a = dictionary.objectForKey("a") as! String

the app crashes at this point with

Could not cast value of type '__NSCFNumber' (0x...) to 'NSString' (0x...).

other numbers inside "" are treated as strings as are numbers outside of strings cast to String without any issue.

Can anyone let me know what's going on? And how to get at these values easily?

like image 710
Damo Avatar asked Dec 17 '25 17:12

Damo


1 Answers

The value is an NSNumber, not an NSString. You can use stringValue to convert it:

if let a = d["a"] as? NSNumber {
    let aString = a.stringValue
    println(aString) // -1
} else {
    // either d doesn't have a value for the key "a", or d does but the value is not an NSNumber
}

If you're sure it exists and is an NSNumber, you can use forced unwrapping, forced casting, and string interpolation:

let a = d["a"]! as! NSNumber
let aString = "\(a)"
like image 132
Aaron Brager Avatar answered Dec 20 '25 07:12

Aaron Brager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!