Generic Instance Method

withUnsafeMutableBufferPointer(_:)

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

Declaration

mutating func withUnsafeMutableBufferPointer<R>(_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R) rethrows -> R

Parameters

body

A closure with an UnsafeMutableBufferPointer 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 withUnsafeMutableBufferPointer(_:) method. The pointer argument is valid only for the duration of the method’s execution.

Return Value

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

Discussion

Often, the optimizer can eliminate bounds checks within an array algorithm, but when that fails, invoking the same algorithm on the buffer pointer passed into your closure lets you trade safety for speed.

The following example shows how modifying the contents of the UnsafeMutableBufferPointer argument to body alters the contents of the array:

var numbers = [1, 2, 3, 4, 5]
numbers.withUnsafeMutableBufferPointer { buffer in
    for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) {
        buffer.swapAt(i, i + 1)
    }
}
print(numbers)
// Prints "[2, 1, 4, 3, 5]"

The pointer passed as an argument to body is valid only during the execution of withUnsafeMutableBufferPointer(_:). Do not store or return the pointer for later use.

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 withUnsafeBytes<R>((UnsafeRawBufferPointer) -> R) -> R

Calls the given closure with a pointer to the underlying bytes of the array’s 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.