Could not cast value of type 'NSTaggedPointerString' to 'NSNumber'
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}
I think this could help you
totalData = Double(jsonDict["totalfup"] as! String)!
The failure reason is that the JSON returns String
values, not numbers.
If the returned JSON data contains only these two key value pairs declare the type as [String:String]
that avoids the type casting.
In any case you have to put the code to update the variables into the "good" branch of the do - catch
expression.
struct Usage { var totalData = 0.0 var remainingTotalData = 0.0 init(jsonData: NSData) { // Swift 3: Data do { let jsonDict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String: String] // Swift 3: let jsonDict = try NSJSONSerialization.jsonObject(with: jsonData) as! [String: String] totalData = Double(jsonDict["totalfup"]!) remainingTotalData = Double(jsonDict["totalrem"]!) } catch { print("Error occurred parsing data: \(error)") } }}