masgar
masgar

Reputation: 1873

Get float value from NSData bytes

how can I write this

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

in swift?

Thanks.

Upvotes: 2

Views: 837

Answers (1)

Martin R
Martin R

Reputation: 539745

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

Upvotes: 2

Related Questions