3

since i converted my Code to Swift 3 the error occurs.

'init is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.

Here is my Code:

func parseHRMData(data : NSData!)
{
    var flags : UInt8
    var count : Int = 1
    var zw = [UInt8](count: 2, repeatedValue: 0)

    flags = bytes[0]
    /*----------------FLAGS----------------*/
        //Heart Rate Value Format Bit
        if([flags & 0x01] == [0 & 0x01])
        {
            //Data Format is set to UINT8
            //convert UINT8 to UINT16
            zw[0] = bytes[count]
            zw[1] = 0
            bpm = UnsafePointer<UInt16>(zw).memory

            print("HRMLatitude.parseData Puls(UINT8): \(bpm)BPM")

            //count field index
            count = count + 1
        }

How can I fix this error?

Thanks in advance!

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382

1 Answers1

4

zw is an array of UInt8. To reinterpret the pointer to the element storage as a pointer to UInt16, withMemoryRebound() has to be called in Swift 3. In your case:

var zw = [UInt8](repeating: 0, count: 2)
// Alternatively:
var zw: [UInt8] = [0, 0]

// ...

let bpm = UnsafePointer(zw).withMemoryRebound(to: UInt16.self, capacity: 1) {
    $0.pointee
}

An alternative solution is

let bpm = zw.withUnsafeBytes {
    $0.load(fromByteOffset: 0, as: UInt16.self)
}

See SE-0107 UnsafeRawPointer API for more information about raw pointers, typed pointers, and rebinding.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Using zw var defined in the question didn't work. It gives me a "Incorrect argument label in call" error. Looks like the API has changed in Swift 3 it is.. `var zw = [UInt8](repeating: 0, count: 2)` If you could edit the answer I will upvote (otherwise it won't let me) – seanbehan Jun 08 '18 at 18:45