Generic Instance Method 総称体インスタンスメソッド

withUnsafeBufferPointer(_:)

Calls a closure with a pointer to the array’s contiguous storage. あるクロージャを配列のもつ隣接ストレージへのポインタとともに呼び出します。

Declaration 宣言

func withUnsafeBufferPointer<R>(_ body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R

Parameters パラメータ

body

A closure with an UnsafeBufferPointer 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 withUnsafeBufferPointer(_:) method. The pointer argument is valid only for the duration of the method’s execution. あるクロージャでUnsafeBufferPointerパラメータを持ち、それはその配列のための隣接ストレージを指し示します。そのようなストレージが存在しないならば、それは作成されます。bodyが戻り値を持つならば、その値はまたwithUnsafeBufferPointer(_:)メソッドの戻り値としても使われます。ポインタ引数は、ただメソッドの実行の間に対してのみ有効です。

Return Value 戻り値

The return value, if any, of the body closure parameter. bodyクロージャパラメータの戻り値、もしあれば。

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 you can iterate over the contents of the buffer pointer: 次の例は、どのようにあなたがバッファポインタの内容にわたって反復できるかを示します:


let numbers = [1, 2, 3, 4, 5]
let sum = numbers.withUnsafeBufferPointer { buffer -> Int in
    var result = 0
    for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) {
        result += buffer[i]
    }
    return result
}
// 'sum' == 9

The pointer passed as an argument to body is valid only during the execution of withUnsafeBufferPointer(_:). Do not store or return the pointer for later use. 引数としてbodyに渡されるポインタは、withUnsafeBufferPointer(_:)の実行の間のみ有効です。後で使うためにポインタを格納したり返したりしないでください。

See Also 参照

Accessing Underlying Storage 基礎をなすストレージにアクセスする