swifttypescastingprimitive-types

How to create a Double value from a Float value in Swift


I can't believe that I can't figure this out myself and I also cant find an answer online, but...

I'm working in Swift after a long break working on Dart and Java.

I have a situation where I have component A supplying a Float value, and component B requiring a Double value. I can't figure out how to convert/cast/re-instantiate the float to a double!

Example:

let f:Float = 0.3453
let d:Double = f 

That assignment doesn't work, even though if f had been an Int, it would have. Which is very surprising to me since a Float is less precise than Double (takes less memory).

I also tried:

let d:Double = f as! Double

XCode warns that this will "always fail."

Also tried:

let d:Double = Double(from: f)

XCode warns "f should be decoder type"

There has to be an extremely obvious/easy solution to this.


Solution

  • As @workingdog said, this will work:

    let f: Float = 0.3453
    let d: Double = Double(f)
    
    print(d) // prints 0.34529998898506165