Search code examples
swiftcastinganyobject

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)")

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?


Solution

  • 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