NSMutableDictionary将NSString值视为NSNumber

时间:2015-04-22 14:50:00

标签: ios swift nsstring nsmutabledictionary nsnumber

我在NSMutableDictionary中有以下值 - 请参阅图像

enter image description here

我试图得到“a”因此:

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

应用程序此时崩溃

无法将“__NSCFNumber”类型的值(0x ...)转换为“NSString”(0x ...)。

“”中的其他数字被视为字符串,因为字符串之外的数字被转换为字符串而没有任何问题。

任何人都可以让我知道发生了什么事吗?以及如何轻松获得这些价值?

1 个答案:

答案 0 :(得分:20)

值为NSNumber,而不是NSString。您可以使用stringValue转换它:

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
}

如果您确定它存在并且是NSNumber,则可以使用强制展开,强制转换和字符串插值:

let a = d["a"]! as! NSNumber
let aString = "\(a)"