Swift:AnyObject强制转换为Float失败 [英] Swift: AnyObject cast to Float failed
问题描述
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)")
我不知道为什么 ss
显示为nil,而 sss
为什么显示 0.599999998
。为什么强制转换为 Float
无效?你们有一些方法可以使我得到正确的结果吗?
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?
推荐答案
0.6
是 Double
文字价值。因此,您不能将其转换为 Float
(需要对其进行转换)。
The 0.6
is a Double
literal value. As such, you can't cast it to Float
(you need to convert it).
尝试以下操作:
let f = Float(json["progress"] as! Double)
或者,如果您不确定如何确定数字的类型这个 AnyObject
成立,更安全的方法是:
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
当然,那些<$ c $如果json值丢失 或您误判了预期的类型,则上述c> as!将会崩溃 hard 。否则,请使用 as?
运算符:)
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 :)
铸造速成班。将已知的 Double
值转换为 Float
时,编译器会为我们提供一个很好的提示:
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
警告:从 Double转换为无关类型 Float总是失败
warning: cast from 'Double' to unrelated type 'Float' always fails
这篇关于Swift:AnyObject强制转换为Float失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!