Search code examples
swiftunsafe-pointers

Unable to understand how withUnsafeBytes method works


I am trying to convert Data to UnsafePointer. I found an answer here where I can use withUnsafeBytes to get the bytes.

Then I did a small test my self to see I could just print out the bytes value of the string "abc"

let testData: Data = "abc".data(using: String.Encoding.utf8)!

testData.withUnsafeBytes(
{(bytes: UnsafePointer<UInt8>) -> Void in

    NSLog("\(bytes.pointee)")

})

But the output is just the value of one character, which is "a".

2018-07-11 14:40:32.910268+0800 SwiftTest[44249:651107] 97

How could I get the byte value of all three characters then?


Solution

  • The "pointer" points to the address of the first byte in the sequence. If you want to want a pointer to the other bytes, you have to use pointer arithmetic, that is, move the pointer to the next address:

    testData.withUnsafeBytes{ (bytes: UnsafePointer<UInt8>) -> Void in
        NSLog("\(bytes.pointee)")
        NSLog("\(bytes.successor().pointee)")
        NSLog("\(bytes.advanced(by: 2).pointee)")
    }
    

    or

    testData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in
        NSLog("\(bytes[0])")
        NSLog("\(bytes[1])")
        NSLog("\(bytes[2])")
    }
    

    However, you must be aware of the byte size of testData and don't overflow it.