Reputation: 2587
Currently looking into swift pointers.
UnsafePointer
and UnsafeMutablePointer
provide a pointer to a byte. By using pointer arithmetic, you can access the rest of the bytes.
Something similar can be done with a UnsafeMutableBufferPointer
, which has an endIndex parameter. So what is the advantage/difference of using UnsafeMutableBufferPointer
over UnsafeMutablePointer
when accessing for example the bytes in NSData
?
Upvotes: 6
Views: 1199
Reputation: 726579
UnsafeMutablePointer<T>
is designed for accessing a single element of type T
. Its interface is designed for accessing a single scalar value.
UnsafeMutableBufferPointer<T>
, on the other hand, is designed to access a group of elements of type T
stored in a contiguous block of memory. Its interface is designed to access individual elements of the range, and also for treating the entire collection as a single unit (e.g. the generate
method).
If you access bytes inside NSData
, UnsafePointer
alone is not sufficient, because you need to know the length of data. In contrast, a single UnsafeBufferPointer
is sufficient to represent the data, because it provides both the initial location and the number of elements.
Upvotes: 2