Swift 3中的UnsafePointer

时间:2016-10-18 15:09:38

标签: ios swift xcode bluetooth unsafe-pointers

我知道这个问题被问了好几次,但我真的不明白。

我想从蓝牙设备(miband)中提取值。 在swift 2中它的工作原理如下:

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    if characteristic.uuid.uuidString == "FF06" {
        let value = UnsafePointer<Int>(characteristic.value!.bytes).memory
        print("Steps: \(value)")
    }
}

但是在swift 3中它会抛出一个错误:

Cannot invoke initializer for type 'UnsafePointer<Int>' with an argument list of type '(UnsafeRawPointer)'

我不知道如何将其迁移到swift 3。

1 个答案:

答案 0 :(得分:2)

您可以将withUnsafeBytespointee

一起使用
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    if characteristic.uuid.uuidString == "FF06" {
        let value = characteristic.value!.withUnsafeBytes { (pointer: UnsafePointer<Int>) -> Int in
            return pointer.pointee
        }
        print("Steps: \(value)")
    }
}

如果UnsafePointer指向Pointee数组,那么您可以使用下标运算符,例如pointer[0]pointer[1]等,而不是pointer.pointee

有关详细信息,请参阅SE-0107