Search code examples
iosswiftxcodebluetoothunsafe-pointers

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.


Solution

  • 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, e.g. pointer[0], pointer[1], etc., rather than pointer.pointee.

    For more information, see SE-0107.