2

I'm looking for the equivalent of Java's Float.intBitsToFloat(int) in Swift.

I've tried:

let myInt: UInt32 = ...
let myFloat = Float(_bits: myInt)

but that gives me the compiler error, "cannot convert value of type 'UInt32' to expected argument type 'FPIEEE32'".

Is there an easy way to do this that I am missing?

Hans Brende
  • 7,847
  • 4
  • 37
  • 44
  • Why use Int32 and Float32 instead of just Int and Float? – Rutger Huijsmans Apr 25 '16 at 04:51
  • The referenced question is about Float to Int32 conversion, but the answers demonstrate the conversion in both directions. – Martin R Apr 25 '16 at 04:55
  • @MartinR Thanks for the help. The answer you link to says that the `_fromBitPattern()` and `_toBitPattern()` methods are no longer visible in the API documentation. According to [this answer](http://stackoverflow.com/a/14029631/2599133), doesn't that mean that these methods are not allowed to be used in iOS apps? – Hans Brende Apr 25 '16 at 06:07
  • 1
    Actually [this](http://stackoverflow.com/questions/26976579/swift-extract-float-from-byte-data) is a better duplicate. I have reopened the question, but cannot close it again. – Those _xxxBitPattern() methods were public at an earlier time, now it might be better to use `unsafeBitCast` (even if I don't like it :) – Martin R Apr 25 '16 at 06:16
  • Possible duplicate of [Swift: extract float from byte data](http://stackoverflow.com/questions/26976579/swift-extract-float-from-byte-data). – Martin R Apr 25 '16 at 06:16

1 Answers1

1

UPDATE: In Swift 3, we can now do:

Float(bitPattern: myInt)

After doing some digging with the help of @MartinR, there appear to be two (rather ugly) Swift solutions:

Float._fromBitPattern(myInt)

and

unsafeBitCast(myInt, Float.self)

The former solution no longer appears to be documented in the public API. Therefore, the latter seems like the better approach.

Hans Brende
  • 7,847
  • 4
  • 37
  • 44