Swift: AnyObject cast to Float failed
Asked Answered
L

1

3
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?

Lorin answered 26/4, 2017 at 1:31 Comment(7)
You should use Any instead of AnyObject let json:[String: Any] = [ "left" : 18, "deadline" : "May 10", "progress" : 0.6 ]Herl
If you would like to store a Float instead of a Double you would need to specify it Float(0.6) otherwise the compiler will infer the type (Double)Herl
I have tried to use Any, but it made no sense.Lorin
Using AnyObject is what doesn't make any sense. Float is a struct not AnyObject. It is stored as NSNumber if you use AnyObjectHerl
using AnyObject the correct approach to get a Float would be (json["progress"] as? NSNumber)?.floatValueHerl
Yeah, you are right. "progress" : Float(0.6). Changing to this makes sense. Thanks for your help.Lorin
You are welcome. Note: no need to cast let js:[String: Any] = [ "left" : 18, "deadline" : "May 10", "progress" : Float(0.6) ]Herl
C
2

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

Cockcrow answered 26/4, 2017 at 1:36 Comment(3)
@LeoDabus Good Leaf here is still learning his way around Swift... failing fast helps a lot! Silent errors not so much...Cockcrow
@LeoDabus To be clear, if we leave it as Float?, he is gonna be using ? all the way and will be completely lost when his code finally crashes down the line. Just look at all those SO newbie questions out there wrongly using ? like crazy haha...Cockcrow
@LeoDabus I somehow feel he is still on that testing phase of yours... :-) Anyway, thanks for the detailed feedback man!Cockcrow

© 2022 - 2024 — McMap. All rights reserved.