Search code examples
iosswiftdoublensjsonserialization

Could not cast value of type 'NSTaggedPointerString' to 'NSNumber'


I have a Swift struct like this.

struct Usage {
    var totalData: Double
    var remainingTotalData: Double

    init(jsonData: NSData) {
        var jsonDict = [String: AnyObject]()

        do {
            jsonDict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String: AnyObject]
        } catch {
            print("Error occurred parsing data: \(error)")
        }

        totalData = jsonDict["totalfup"] as! Double
        remainingTotalData = jsonDict["totalrem"] as! Double
    }
}

From an API, I get the following JSON response. This is the println of the jsonDict variable.

[
    "totalfup": 96.340899, 
    "totalrem": 3548710948
]

When I try to assign the value of the totalfup to the property totalData, I get this error.

Could not cast value of type 'NSTaggedPointerString' to 'NSNumber'

Anyone knows why? I tried changing the property type to float and then the whole struct to class but still the issue occurs.


Solution

  • The reason of the error is jsonDict["totalfup"] is a String (NSTaggedPointerString is a subclass of NSString) , so you should convert String to Double.

    Please make sure, catch exception and check type before force-unwrap !

    totalData = (jsonDict["totalfup"] as! NSString).doubleValue
    

    For safety, using if let:

    // check dict["totalfup"] is a String?
    if let totalfup = (dict["totalfup"] as? NSString)?.doubleValue {
      // totalfup is a Double here 
    }
    else {
      // dict["totalfup"] isn't a String
      // you can try to 'as? Double' here
    }