iOS Swift:无法将值类型“__NSCFNumber”转换为“NSString” [英] iOS Swift: Could not cast value type '__NSCFNumber' to 'NSString'

查看:1326
本文介绍了iOS Swift:无法将值类型“__NSCFNumber”转换为“NSString”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从我的Firebase数据库(JSON数据库)中检索数字值,然后将这个数字显示到 textField 中,但是当我尝试显示该错误时。

lockquote

无法将值类型'__NSCFNumber'转换为'NSString'

如何正确地将检索到的值转换为一个字符串,并考虑到这个值可能会在字符串和数字之间发生变化。



这是我的代码:

  let quantity = child.childSnapshot(forPath:quantity)。value //从Firebase获取价值

//检查数量是否存在,然后将字符串添加到对象中。
if(!(quantity is NSNull)&&((quantity as!String)!=)){
newDetail.setQuantity(quantity:quantity as!String)
}


解决方案

错误是说你的数量是 Number ,你不能直接将数字转换为 String ,试试这样。



< pre $ newDetail.setQuantity(quantity:\(quantity))



 如果让quantity = child.childSnapshot(forPath:quantity)。value as? NSNumber {
newDetail.setQuantity(quantity:quantity.stringValue)
}
否则如果让quantity = child.childSnapshot(forPath:quantity)。value as?字符串{
newDetail.setQuantity(quantity:quantity)
}

Single if语句

 如果让数量= child.childSnapshot(forPath:quantity)。value,
(num是NSNumber || num是字符串){
newDetail.setQuantity(数量:\(数量))
}

使用第二个和第三个选项不需要检查零。


I am retrieving a number value from my Firebase database (JSON db) and then displaying this number into a textField, although I get this error when I try to display it.

Could not cast value type '__NSCFNumber' to 'NSString'

How can I properly convert the retrieved value to a String, taking into consideration that this value maybe change between a String and a Number when I retrieve it.

Here is my code:

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)
}

解决方案

The error is saying that your quantity is Number and you cannot directly convert number to String, try like this.

newDetail.setQuantity(quantity: "\(quantity)")

Or

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)
} 

Or With Single if statement

if let quantity = child.childSnapshot(forPath: "quantity").value,
   (num is NSNumber || num is String) {
     newDetail.setQuantity(quantity: "\(quantity))
}

Using second and third option there is no need to check for nil.

这篇关于iOS Swift:无法将值类型“__NSCFNumber”转换为“NSString”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆