The Data
type in Swift holds onto a raw stream of bytes. Accessing these bytes is done with
the Unsafe API which provides
direct access to these bytes within an instance of Data
. Legacy code which uses NSData
is
still sometimes used because it is familiar. The copyBytes:length:
function can be used
to copy the bytes into an array by referencing a pointer. It is best to instead use the
modern Swift API for accessing bytes.
See the included extension as well as the playground which demonstrate how the modern Swift API can be used.
Credit: sharplet
The extension is deprecated for Swift 5
"'withUnsafeBytes' is deprecated: use
withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R
instead"I'm attempting to write my first Swift app and am too green to understand how to modify the extension (I thank you for it, though).