n00bAppDev n00bAppDev - 7 days ago 6
Swift Question

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

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

Answer

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

if let quantity = child.childSnapshot(forPath: "quantity").value {
     newDetail.setQuantity(quantity: "\(quantity))
}

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

Comments