Generic Instance Method

withMemoryRebound(to:capacity:_:)

Executes the given closure while temporarily binding the specified number of instances to the given type.

Declaration

func withMemoryRebound<T, Result>(to type: T.Type, capacity count: Int, _ body: (UnsafeMutablePointer<T>) throws -> Result) rethrows -> Result

Parameters

type

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

count

The number of instances of Pointee to bind to type.

body

A closure that takes a mutable typed pointer to the same memory as this pointer, only bound to type T. The closure’s pointer 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:capacity:_:) method.

Return Value

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

Discussion

Use this method when you have a pointer to memory bound to one type and you need to access that memory as instances of another type. Accessing memory as a 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 region of memory starting at this pointer and covering count instances of the pointer’s Pointee type must be initialized.

The following example temporarily rebinds the memory of a UInt64 pointer to Int64, then accesses a property on the signed integer.

let uint64Pointer: UnsafeMutablePointer<UInt64> = fetchValue()
let isNegative = uint64Pointer.withMemoryRebound(to: Int64.self) { ptr in
    return ptr.pointee < 0
}

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

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