我正在从我的 Firebase 数据库 (JSON db) 中检索一个数字值,然后将这个数字显示到一个 textField
中,尽管我在尝试显示它时遇到了这个错误。
Could not cast value type '__NSCFNumber' to 'NSString'
如何正确地将检索到的值转换为字符串,并考虑到检索时该值可能会在字符串和数字之间变化。
这是我的代码:
let quantity = child.childSnapshot(forPath: "quantity").value // Get value from Firebase
// Check if the quantity exists, then add to object as string.
if (!(quantity is NSNull) && ((quantity as! String) != "")) {
newDetail.setQuantity(quantity: quantity as! String)
}
最佳答案
错误是说你的数量是Number
,你不能直接把number转换成String
,这样试试。
newDetail.setQuantity(quantity: "\(quantity)")
或者
if let quantity = child.childSnapshot(forPath: "quantity").value as? NSNumber {
newDetail.setQuantity(quantity: quantity.stringValue)
}
else if let quantity = child.childSnapshot(forPath: "quantity").value as? String {
newDetail.setQuantity(quantity: quantity)
}
或使用单个 if 语句
if let quantity = child.childSnapshot(forPath: "quantity").value,
(num is NSNumber || num is String) {
newDetail.setQuantity(quantity: "\(quantity))
}
使用第二个和第三个选项不需要检查 nil。
关于iOS swift : Could not cast value type '__NSCFNumber' to 'NSString' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40798220/