iOS swift : Could not cast value type '__NSCFNumber' to 'NSString'

标签 ios swift firebase

我正在从我的 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/

相关文章:

android - FCM 中的 token 更新

Firebase 3存储不允许文件更新/覆盖

ios - 是否有任何选项可以将测试版本分发给超过 100 名测试人员?

ios - 以一定角度将文本绘制到图像上 [Swift 3]

ios - 从 iOS 应用程序发推文时卡片不显示包含图像

ios - 如何在 UINavigationItem titleView 中创建淡入/淡出动画?

swift - 在 Swift 中从两个 NSWindows 传递变量

java - 当数据更改时,Firebase 不会检索最后的数据,并且不会以正确的方式执行 addValueEventListener 内的条件

ios - UIWebview 不播放 mp4 视频

ios - 自动布局中的 viewDidLayoutSubviews 在 UIPageViewController 上旋转