Type Method

allocate(capacity:)

Allocates uninitialized memory for the specified number of instances of type Pointee.

Declaration

static func allocate(capacity count: Int) -> UnsafeMutablePointer<Pointee>

Parameters

count

The amount of memory to allocate, counted in instances of Pointee.

Discussion

The resulting pointer references a region of memory that is bound to Pointee and is count * MemoryLayout<Pointee>.stride bytes in size.

The following example allocates enough new memory to store four Int instances and then initializes that memory with the elements of a range.

let intPointer = UnsafeMutablePointer<Int>.allocate(capacity: 4)
for i in 0..<4 {
    (intPointer + i).initialize(to: i)
}
print(intPointer.pointee)
// Prints "0"

When you allocate memory, always remember to deallocate once you’re finished.

intPointer.deallocate()