简体   繁体   English

Swift 3 中的 UnsafePointer

[英]UnsafePointer in Swift 3

I know this question was asked several times but I really don't understand it.我知道这个问题被问了好几次,但我真的不明白。

I want to extract a value from a bluetooth device (miband).我想从蓝牙设备(miband)中提取一个值。 In swift 2 it worked like this:在 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)")
    }
}

But in swift 3 it throws an error:但是在 swift 3 中它会抛出一个错误:

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

And I have no idea how to migrate that to swift 3.而且我不知道如何将其迁移到 swift 3。

You can use withUnsafeBytes with pointee :您可以使用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)")
    }
}

If the UnsafePointer was pointing to an array of Pointee , then you could use the subscript operator, eg pointer[0] , pointer[1] , etc., rather than pointer.pointee .如果UnsafePointer指着的数组Pointee ,则可以使用下标操作符,例如pointer[0] pointer[1]等等,而不是pointer.pointee

For more information, see SE-0107 .有关更多信息,请参阅SE-0107

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM