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?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Leaf
  • 203
  • 1
  • 2
  • 13
  • 1
    You should use Any instead of AnyObject `let json:[String: Any] = [ "left" : 18, "deadline" : "May 10", "progress" : 0.6 ]` – Leo Dabus Apr 26 '17 at 01:42
  • 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) – Leo Dabus Apr 26 '17 at 01:45
  • I have tried to use Any, but it made no sense. – Leaf Apr 26 '17 at 01:46
  • 1
    Using AnyObject is what doesn't make any sense. Float is a struct not AnyObject. It is stored as NSNumber if you use AnyObject – Leo Dabus Apr 26 '17 at 01:47
  • using AnyObject the correct approach to get a Float would be `(json["progress"] as? NSNumber)?.floatValue` – Leo Dabus Apr 26 '17 at 01:50
  • 1
    Yeah, you are right. `"progress" : Float(0.6)`. Changing to this makes sense. Thanks for your help. – Leaf Apr 26 '17 at 01:50
  • You are welcome. Note: no need to cast `let js:[String: Any] = [ "left" : 18, "deadline" : "May 10", "progress" : Float(0.6) ]` – Leo Dabus Apr 26 '17 at 01:53

1 Answers1

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

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
  • @LeoDabus Good Leaf here is still learning his way around Swift... failing fast helps a lot! Silent errors not so much... – Paulo Mattos Apr 26 '17 at 02:32
  • @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... – Paulo Mattos Apr 26 '17 at 02:41
  • @LeoDabus I somehow feel he is still on that *testing* phase of yours... :-) Anyway, thanks for the detailed feedback man! – Paulo Mattos Apr 26 '17 at 02:55