1
    let data = Data()    
    data.withUnsafeBytes { (uPtr: UnsafePointer<UInt8>) in   
        var ptr = uPtr   
        var j = ptr.pointee
        var new = ptr.advanced(by: 1)    
    }   

What does j represent or store here, is it pointing to the next byte of the data? Will new variable store the next byte? Any Link To Learn Pointer in A Simpler Way In Swift And What Are the Advantages of using pointer in Swift?

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
Amey
  • 795
  • 8
  • 31

1 Answers1

4

pointee is the value being stored and pointed to by the pointer. It used to be called memory in earlier versions of Swift. Don't use pointers in Swift unless you absolutely must, because it involves you in retaining and releasing memory manually:

UnsafePointer provides no automated memory management or alignment guarantees. You are responsible for handling the life cycle of any memory you work with through unsafe pointers to avoid leaks or undefined behavior.

In your example you have no data but if you were to have data then the first pointer would first of all point to the memory address of the first value in the data array, e.g.

var str = "Hello, playground"

guard let data = str.data(using: .utf8) else {fatalError()}
data.withUnsafeBytes { (uPtr: UnsafePointer<UInt8>) in
    let ptr = uPtr
    ptr.pointee // 72
    let ptr2 = ptr.advanced(by: 1)
    ptr2.pointee // 101
}

So here we'd expect ptr.pointee to be the utf8 value of "H" which is 72, and when we advance by 1 we then have a pointer to the value of "e" which is 101, i.e. we are working our way through the Array. But you wouldn't want to actually do this because it assumes that the memory addresses for each item in the array are contiguous, which they might not be.

A more sober approach to retrieving the bytes would be:

    data.withUnsafeBytes { [UInt8](UnsafeBufferPointer(start:$0, count:data.count))
}

or better still:

[UInt8](data)

As outlined in this post.

sketchyTech
  • 5,746
  • 1
  • 33
  • 56