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

梦想与她 提交于 2019-12-12 13:46:33

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/43102493/init-is-unavailable-use-withmemoryreboundtocapacity-to-temporarily-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!