0Pricing
Swift Academy · Lesson

Unsafe Buffer Pointers

Process contiguous memory efficiently.

What a Buffer Pointer Is

A single typed pointer addresses one element at a time. An UnsafeBufferPointer<T> wraps a start pointer plus a count, giving you a bounded view over a contiguous block of memory that conforms to Collection.

That means you can iterate, subscript, map, and reduce — all the familiar collection APIs over raw memory.

// A buffer pointer = base address + element count
// UnsafeBufferPointer<Int>(start: ptr, count: 5)

Read-Only vs Mutable Buffers

Like single pointers, buffers come in two flavors: UnsafeBufferPointer<T> for read-only iteration and UnsafeMutableBufferPointer<T> when you also need to assign elements.

let p = UnsafeMutablePointer<Int>.allocate(capacity: 4)
p.initialize(repeating: 0, count: 4)
let buf = UnsafeMutableBufferPointer(start: p, count: 4)
buf[0] = 11
print(buf[0]) // 11

All lessons in this course

  1. MemoryLayout and Alignment
  2. UnsafePointer and UnsafeMutablePointer
  3. Unsafe Buffer Pointers
  4. withUnsafeBytes and C Interop
← Back to Swift Academy