简体   繁体   中英

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). In swift 2 it worked like this:

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:

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.

You can use withUnsafeBytes with pointee :

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 .

For more information, see SE-0107 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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