Swift 转换为有符号16位数组时出现问题

Swift 转换为有符号16位数组时出现问题,swift,pointers,bluetooth-lowenergy,Swift,Pointers,Bluetooth Lowenergy,我正在通过BLE从传感器检索数据。 我正在将NSData中的字节转换为有符号16位整数数组。然而,我得到了一个错误的说法 Argument type '[Int16]' does not conform to expected type '_Pointer' 有更好的办法吗?感谢您的帮助 func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteris

我正在通过BLE从传感器检索数据。 我正在将NSData中的字节转换为有符号16位整数数组。然而,我得到了一个错误的说法

Argument type '[Int16]' does not conform to expected type '_Pointer'
有更好的办法吗?感谢您的帮助

func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {

    if characteristic.uuid == tempUUID {

        let dataBytes = characteristic.value
        let dataCount = dataBytes?.count

        var dataArray = [Int16](repeating: 0, count: dataCount!)
        dataBytes.getBytes(dataArray, length:dataCount! * MemoryLayout<Int16>.size)

        let finalAnswer = Double(dataArray[1])/128

这就是如何将数据复制到整数数组Swift 3/4中:

if let data = characteristic.value {
    var dataArray = [Int16](repeating: 0, count: data.count/MemoryLayout<Int16>.stride)
    dataArray.withUnsafeMutableBufferPointer {
        _ = data.copyBytes(to: $0)
    }
    let finalAnswer = Double(dataArray[1])/128
}
如果您只需要一个值,则可以访问该值,而无需 创建阵列:

if let data = characteristic.value {
    let i16value = data.withUnsafeBytes { (ptr: UnsafePointer<Int16>) in
        ptr[1]
    }
    let finalAnswer = Double(i16value)/128
}
另一种选择:

if let data = characteristic.value {
    let i16value = data.subdata(in: 2..<4).withUnsafeBytes {
        UnsafeRawPointer($0).load(as: Int16.self)
    }
    let finalAnswer = Double(i16value)/128
}