Search code examples
iosswiftnsdata

Get float value from NSData bytes


how can I write this

float value = *(float *)[data bytes];

in swift?

Thanks.


Solution

  • The corresponding Swift code is

    let value = UnsafePointer<Float>(data.bytes).memory
    

    which – as your Objective-C code – assumes that the NSData objects has (at least) 4 bytes, representing a floating point value in host byte order.

    • UnsafePointer<Float>(..) corresponds to the (float *) cast.
    • .memory corresponds to the dereferencing operator *.

    An alternative is

    var value : Float = 0
    data.getBytes(&value, length: sizeofValue(value))