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. あるクロージャでUnsafeRawBufferPointerパラメータを持ち、それはその配列のための隣接ストレージを指し示します。そのようなストレージが存在しないならば、それは作成されます。bodyが戻り値を持つならば、その値はまたwithUnsafeBytes(_:)メソッドの戻り値としても使われます。引数は、ただクロージャの実行の間に対してのみ有効とされます。

Return Value 戻り値

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

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. この配列の持つElement型は自明型でなければなりません、それは単にビット対ビットコピーでコピーされることが、何らかの間接参照または参照カウント操作なしで可能です。一般に、生粋のSwift型で強いまたは弱い参照を含まないものは自明です、インポートされたCのstructとenumのように。

The following example copies the bytes of the numbers array into a buffer of UInt8: 以下の例は、numbers配列のバイトをUInt8のバッファへとコピーします:


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

See Also 参照

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