Swift: AnyObject cast to Float failed

混江龙づ霸主 提交于 2019-12-21 22:16:26

问题


let json = [
    "left" : 18,
    "deadline" : "May 10",
    "progress" : 0.6
] as [String: AnyObject]

let ss = json["progress"] as? Float
let sss = json["progress"] as? Double
print("ss = \(ss)\n  sss = \(sss)")

I have no idea why the ss shows nil while sss shows 0.599999998. Why does casting to Float get nil? Do you guys have some methods so that I can get the correct result?


回答1:


The 0.6 is a Double literal value. As such, you can't cast it to Float (you need to convert it).

Try this instead:

let f = Float(json["progress"] as! Double)

Or, if you aren't really sure what type of number this AnyObject holds, the safer approach would be:

let f = (json["progress"] as! NSNumber).floatValue

Of course, those as! above will crash hard if the json value is missing or you misjudge the expected type. Use the as? operator instead if you feel otherwise :)


Casting crash course. When casting a known Double value to a Float, the compiler gives us a nice heads up about this:

let d = 0.6
let f = d as? Float

warning: cast from 'Double' to unrelated type 'Float' always fails



来源:https://stackoverflow.com/questions/43623530/swift-anyobject-cast-to-float-failed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!