Generic Instance Method

withUnsafeBytes(_:)

Calls the given closure with a pointer to the underlying bytes of the array’s contiguous storage.

Declaration

func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R

Parameters

body

A closure with an UnsafeRawBufferPointer parameter that points to the contiguous storage for the array. If no such storage exists, it is created. If body has a return value, that value is also used as the return value for the withUnsafeBytes(_:) method. The argument is valid only for the duration of the closure’s execution.

Return Value

The return value, if any, of the body closure parameter.

Discussion

The array’s Element type must be a trivial type, which can be copied with just a bit-for-bit copy without any indirection or reference-counting operations. Generally, native Swift types that do not contain strong or weak references are trivial, as are imported C structs and enums.

The following example copies the bytes of the numbers array into a buffer of UInt8:

var numbers = [1, 2, 3]
var byteBuffer: [UInt8] = []
numbers.withUnsafeBytes {
    byteBuffer.append(contentsOf: $0)
}
// byteBuffer == [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, ...]

See Also

Accessing Underlying Storage

func withUnsafeBufferPointer<R>((UnsafeBufferPointer<Element>) -> R) -> R

Calls a closure with a pointer to the array’s contiguous storage.

func withUnsafeMutableBufferPointer<R>((inout UnsafeMutableBufferPointer<Element>) -> R) -> R

Calls the given closure with a pointer to the array’s mutable contiguous storage.

func withUnsafeMutableBytes<R>((UnsafeMutableRawBufferPointer) -> R) -> R

Calls the given closure with a pointer to the underlying bytes of the array’s mutable contiguous storage.

func withContiguousStorageIfAvailable<R>((UnsafeBufferPointer<Element>) -> R) -> R?

Call body(p), where p is a pointer to the collection’s contiguous storage. If no such storage exists, it is first created. If the collection does not support an internal representation in a form of contiguous storage, body is not called and nil is returned.

func withContiguousMutableStorageIfAvailable<R>((inout UnsafeMutableBufferPointer<Element>) -> R) -> R?

Call body(p), where p is a pointer to the collection’s mutable contiguous storage. If no such storage exists, it is first created. If the collection does not support an internal representation in a form of mutable contiguous storage, body is not called and nil is returned.