Swift 3 中的不安全指针

UnsafePointer in Swift 3

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

我想从蓝牙设备 (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.

您可以将 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