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

n00*_*Dev 7 ios firebase swift

我正在从我的Firebase数据库(JSON数据库)中检索一个数字值,然后将此数字显示为a textField,尽管我在尝试显示它时遇到此错误.

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

我如何正确地将检索到的值转换为String,考虑到当我检索它时,这个值可能会在String和Number之间发生变化.

这是我的代码:

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)
}
Run Code Online (Sandbox Code Playgroud)

Nir*_*v D 19

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

newDetail.setQuantity(quantity: "\(quantity)")
Run Code Online (Sandbox Code Playgroud)

要么

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)
} 
Run Code Online (Sandbox Code Playgroud)

或使用单个if语句

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

使用第二个和第三个选项,无需检查nil.


A.G*_*A.G 11

斯威夫特4:

let rollNumber:String = String(format: "%@", rollNumberWhichIsANumber as! CVarArg)
Run Code Online (Sandbox Code Playgroud)