Generic Instance Method

withMemoryRebound(to:_:)

Executes the given closure while temporarily binding the memory referenced by this buffer to the given type.

Declaration

func withMemoryRebound<T, Result>(to type: T.Type, _ body: (UnsafeMutableBufferPointer<T>) throws -> Result) rethrows -> Result

Parameters

type

The type to temporarily bind the memory referenced by this buffer. The type T must have the same size and be layout compatible with the pointer’s Element type.

body

A closure that takes a mutable typed buffer to the same memory as this buffer, only bound to type T. The buffer argument contains the same number of complete instances of T as the original<br/>buffer’s count. The closure’s buffer argument is valid only for the duration of the closure’s execution. If body has a return value, that value is also used as the return value for the withMemoryRebound(to:_:) method.

Return Value

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

Discussion

Use this method when you have a buffer of memory bound to one type and you need to access that memory as a buffer of another type. Accessing memory as type T requires that the memory be bound to that type. A memory location may only be bound to one type at a time, so accessing the same memory as an unrelated type without first rebinding the memory is undefined.

The entire region of memory referenced by this buffer must be initialized.

Because this buffer’s memory is no longer bound to its Element type while the body closure executes, do not access memory using the original buffer from within body. Instead, use the body closure’s buffer argument to access the values in memory as instances of type T.

After executing body, this method rebinds memory back to the original Element type.