Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
}
like image 716
n00bAppDev Avatar asked Nov 25 '16 05:11

n00bAppDev


4 Answers

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.

like image 112
Nirav D Avatar answered Oct 18 '22 15:10

Nirav D


Swift 4:

let rollNumber:String = String(format: "%@", rollNumberWhichIsANumber as! CVarArg)
like image 42
Alvin George Avatar answered Oct 18 '22 15:10

Alvin George


You may convert your NSNumber value to string like this too, its more traditional and basic approach to format a string

 newDetail.setQuantity(String(format: "%@", quantity))
like image 4
Devang Tandel Avatar answered Oct 18 '22 15:10

Devang Tandel


Swift 4.

 newDetail.setQuantity(String(describing: rollNumberWhichIsANumber))
like image 4
Joyal Clifford Avatar answered Oct 18 '22 15:10

Joyal Clifford