A nonowning collection interface to the bytes in a region of memory.
SDK
- Xcode 8.0+
Framework
- Swift Standard Library
Declaration
Overview
You can use an Unsafe
instance in low-level operations to eliminate uniqueness checks and release mode bounds checks. Bounds checks are always performed in debug mode.
An Unsafe
instance is a view of the raw bytes in a region of memory. Each byte in memory is viewed as a UInt8
value independent of the type of values held in that memory. Reading from memory through a raw buffer is an untyped operation.
In addition to its collection interface, an Unsafe
instance also supports the load(from
method provided by Unsafe
, including bounds checks in debug mode.
To access the underlying memory through typed operations, the memory must be bound to a trivial type.
Note
A trivial type can be copied bit for bit with no indirection or reference-counting operations. Generally, native Swift types that do not contain strong or weak references or other forms of indirection are trivial, as are imported C structs and enums. Copying memory that contains values of nontrivial types can only be done safely with a typed pointer. Copying bytes directly from nontrivial, in-memory values does not produce valid copies and can only be done by calling a C API, such as memmove()
.
UnsafeRawBufferPointer Semantics
An Unsafe
instance is a view into memory and does not own the memory that it references. Copying a variable or constant of type Unsafe
does not copy the underlying memory. However, initializing another collection with an Unsafe
instance copies bytes out of the referenced memory and into the new collection.
The following example uses some
, an Unsafe
instance, to demonstrate the difference between assigning a buffer pointer and using a buffer pointer as the source for another collection’s elements. Here, the assignment to dest
creates a new, nonowning buffer pointer covering the first n
bytes of the memory that some
references—nothing is copied:
Next, the bytes referenced by dest
are copied into byte
, a new [UInt]
array, and then the remainder of some
is appended to byte
: