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’

  • facebook Security Warning while user has enabled secure login - iPhone
  • JSON-data from iOS into PHP-script
  • iOS Bar Item image displaying wrong color
  • Using MMDrawer only in sub navigation view
  • Why are PNG images larger in the iOS app bundle than in my project?
  • Round some corners of UIView and round the view’s layer’s border too
  • 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)
    }
    

    2 Solutions Collect From Internet About “iOS Swift: Could not cast value type '__NSCFNumber' to 'NSString'”

    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.

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