【问题标题】:'init is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type'init 不可用:使用 'withMemoryRebound(to:capacity:_)' 临时将内存视为另一种布局兼容类型
【发布时间】:2017-08-23 11:18:42
【问题描述】:

因为我将我的代码转换为 Swift 3,所以发生了错误。

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

这是我的代码:

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
        }

我该如何解决这个错误?

提前致谢!

【问题讨论】:

    标签: swift swift3 unsafe-pointers


    【解决方案1】:

    zwUInt8 的数组。重新解释指向元素的指针 存储作为指向UInt16withMemoryRebound() 的指针必须是 在 Swift 3 中调用。在你的情况下:

    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
    }
    

    另一种解决方案是

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

    SE-0107 UnsafeRawPointer API 有关原始指针、类型化指针和重新绑定的更多信息。

    【讨论】:

    • 使用问题中定义的 zw var 不起作用。它给了我一个“调用中的参数标签不正确”错误。看起来 API 在 Swift 3 中发生了变化。var zw = [UInt8](repeating: 0, count: 2) 如果你可以编辑答案,我会投票赞成(否则不会让我投票)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 2019-10-16
    相关资源
    最近更新 更多