由于我将我的代码转换为 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
}
我该如何修复这个错误?
提前致谢!
最佳答案
zw 是一个 UInt8 的数组。重新解释指向元素的指针
存储为指向 UInt16 的指针,withMemoryRebound() 必须是
在 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为了 有关原始指针、类型化指针和重新绑定(bind)的更多信息。
关于swift - 'init 不可用 : use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43102493/