Search code examples
swiftswift3unsafe-pointers

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


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!


Solution

  • 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.