无法将“NSTaggedPointerString”类型的值转换为“NSNumber” [英] Could not cast value of type 'NSTaggedPointerString' to 'NSNumber'

查看:1907
本文介绍了无法将“NSTaggedPointerString”类型的值转换为“NSNumber”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的Swift结构。

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

从API中,我得到以下JSON响应。这是 jsonDict 变量的println。

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

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

当我尝试将 totalfup 的值分配给属性 totalData 时,我收到此错误。

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

无法将'NSTaggedPointerString'类型的值转换为'NSNumber'

任何人都知道为什么?我尝试将属性类型更改为 float ,然后将整个结构更改为类,但问题仍然存在。

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

推荐答案

错误的原因是 jsonDict [totalfup] 是一个字符串,所以你应该将String转换为Double。

The reason of the error is jsonDict["totalfup"] is a String, so you should convert String to Double.

请确保在强制解包前捕获异常并检查类型

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

For安全,使用如果让

if let totalfup = (dict["totalfup"] as? NSString)?.doubleValue {
}    

这篇关于无法将“NSTaggedPointerString”类型的值转换为“NSNumber”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆