因为我将我的代码转换为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
}
如何解决此错误?
提前致谢!
答案 0 :(得分:4)
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 有关原始指针,类型指针和重新绑定的更多信息。