DEV Community

Dheerendra Chaturvedi
Dheerendra Chaturvedi

Posted on

Span, InlineArray and ~Escapable in Practice: Safe Low-Level Memory in Swift 6.2

For as long as I've written performance-sensitive Swift, "go fast" has meant "reach for withUnsafeBufferPointer". When you need to parse a binary packet, checksum a blob, or walk a buffer without paying for bounds checks on a Collection you don't fully trust the optimizer to hoist, the unsafe pointer APIs were the only real option. They work. They're also a trap: the pointer is valid for exactly the duration of the closure, and nothing in the type system stops you — or the person who refactors your code next quarter — from letting it escape. One stray return buffer.baseAddress and you have a use-after-free that compiles cleanly and crashes in production.

Swift 6.2 finally gives us the tools to do this work safely: Span and RawSpan, MutableSpan, InlineArray, and the ~Escapable machinery that makes all of it sound. I spent a weekend porting some buffer-wrangling code to them and writing a small package (SpanPlayground) to pin down what actually works today. This is the practical write-up: what each piece does, where it helps, and where it still bites.

All the snippets below are lifted from that package, which builds warning-free in Swift 6 language mode against the macOS 26 / iOS 26 SDK.

Span and RawSpan: a pointer you can't dangle

Span<T> (SE-0447, Span: Safe Access to Contiguous Storage) is a non-escapable, bounds-checked view over contiguous memory. It's the moral equivalent of UnsafeBufferPointer, except the compiler tracks its lifetime for you. You get one by asking a type for it — Array, ArraySlice, ContiguousArray, Data and friends gained span properties via SE-0456, Add Span-providing Properties to Standard Library Types.

public static func sum(_ numbers: [Int]) -> Int {
  let span = numbers.span            // Span<Int>, borrows `numbers`
  var total = 0
  for i in span.indices {
    total += span[i]                 // bounds-checked subscript
  }
  return total
}
Enter fullscreen mode Exit fullscreen mode

The important part is invisible: span borrows numbers, and the compiler will not let span outlive it. There's no closure scope to remember, no "valid only until…" comment to get stale. You use it like a normal value and the borrow checker does the bookkeeping.

RawSpan is the untyped sibling — a safe view of raw bytes, for when you're parsing a wire format rather than reading homogeneous elements. You can get one from Data.bytes, or reinterpret a typed Span with .bytes:

public static func checksum(_ data: Data) -> UInt8 {
  let raw: RawSpan = data.bytes      // RawSpan over Data's storage
  var acc: UInt8 = 0
  for offset in 0..<raw.byteCount {
    acc = acc &+ raw.unsafeLoad(fromByteOffset: offset, as: UInt8.self)
  }
  return acc
}
Enter fullscreen mode Exit fullscreen mode

unsafeLoad is still called "unsafe" because you assert the type and offset are sensible — but the span's byteCount is right there, and reads are checked against it. The "unsafe" surface area has shrunk from "this entire pointer is my problem" to "I'm asserting this one offset holds this one type".

MutableSpan: in-place edits without the exclusivity dance

Reading is half the story. SE-0467, MutableSpan and MutableRawSpan gives you the mutable view. mutableSpan takes an exclusive borrow of the array — while it's alive, the array is inaccessible through any other path, which is exactly the law of exclusivity, now enforced on a view type:

public static func scale(_ numbers: inout [Int], by factor: Int) {
  var span = numbers.mutableSpan     // exclusive borrow
  for i in span.indices {
    span[i] *= factor
  }
  _ = consume span                   // end the borrow before `numbers` is read
}
Enter fullscreen mode Exit fullscreen mode

The one new habit here is consume span. Because the mutable span holds an exclusive borrow, you end that borrow explicitly when you're done, so the caller can read the array again. In practice it's one line at the end of the function, and if you forget it where it matters, the compiler tells you.

This is the API I was most relieved to find. In-place mutation through a buffer pointer always made me nervous about aliasing; MutableSpan makes the exclusive access a property of the type rather than a rule I have to keep in my head.

InlineArray: fixed-size storage, no heap

InlineArray<let N: Int, Element> (SE-0453, InlineArray, a fixed-size array) is the one I've wanted for years. The length is part of the type and the elements are stored inline — in the stack frame or the enclosing struct — so a local InlineArray needs no heap allocation and no reference counting. It's the Swift answer to a C array member, with bounds checks.

A fixed-capacity ring buffer becomes a value type with zero indirection:

public struct RingBuffer4: Sendable {
  private var storage: InlineArray<4, Int>
  private var head = 0
  private var filled = 0
  private var capacity: Int { storage.count }

  public init() { storage = InlineArray<4, Int>(repeating: 0) }

  public mutating func push(_ value: Int) {
    if filled < capacity {
      storage[(head + filled) % capacity] = value
      filled += 1
    } else {
      storage[head] = value            // overwrite oldest
      head = (head + 1) % capacity
    }
  }
  // ...
}
Enter fullscreen mode Exit fullscreen mode

There are two initializers worth knowing: init(repeating:) for a uniform fill, and a closure form that fills each slot from its index — handy for stack-local lookup tables or unpacking fixed records:

public static func squares() -> InlineArray<8, Int> {
  InlineArray<8, Int> { index in index * index }
}
Enter fullscreen mode Exit fullscreen mode

Because the size is static, this whole table lives on the stack. No allocation, nothing to deallocate, and it's trivially Sendable when its element is.

Swift 6.2 also adds a type sugar for it (SE-0483): [4 of Int] is the same type as InlineArray<4, Int>.

One thing that surprises people: InlineArray is not a Sequence or Collection. There's no for x in table and no map. You iterate over table.indices instead, or take a table.span and work with that.

~Escapable and lifetimes: how it's all sound

Everything above rests on SE-0446, Nonescapable Types. A ~Escapable type is one the compiler guarantees cannot outlive what it borrows — it can't be returned, captured by an escaping closure, or stored somewhere longer-lived than its source. Span is ~Escapable; that's why it can't dangle. SE-0465, Standard Library Primitives for Nonescapable Types rounds out the supporting cast.

You can build your own. Here's a minimal byte view that borrows a pointer:

public struct ByteView: ~Escapable {
  private let base: UnsafePointer<UInt8>
  public let count: Int

  @_lifetime(borrow base)
  public init(base: UnsafePointer<UInt8>, count: Int) {
    self.base = base
    self.count = count
  }

  public subscript(index: Int) -> UInt8 {
    precondition(index >= 0 && index < count, "ByteView index out of range")
    return base[index]
  }
}
Enter fullscreen mode Exit fullscreen mode

The @_lifetime(borrow base) annotation is the contract: this view's lifetime is tied to base. Now watch what the compiler refuses:

static func escapingView(_ bytes: [UInt8]) -> ByteView {
  bytes.withUnsafeBufferPointer { buffer in
    ByteView(base: buffer.baseAddress!, count: buffer.count)
  }
}
// error: lifetime-dependent value escapes its scope
//   note: it depends on the lifetime of argument 'buffer'
Enter fullscreen mode Exit fullscreen mode

That's the whole pitch. The view borrows buffer, which only exists inside withUnsafeBufferPointer; returning it would leave a dangling pointer, so the program does not build. The exact bug that unsafe pointers let you ship is now a compile error.

One honest caveat: the @_lifetime spelling is still experimental in Swift 6.2. It requires -enable-experimental-feature Lifetimes (I set it in Package.swift), and the underscore signals that the finalized, un-underscored attribute is still settling. The lifetime-dependency annotations haven't shipped as a finalized Evolution proposal yet — they remain gated behind the experimental flag. If you build your own ~Escapable types today, expect the attribute name to change.

A real parsing example

Here's where it earns its keep. Parsing a fixed binary header — magic, version, flags, length, checksum — straight out of a RawSpan, big-endian on the wire, with zero intermediate allocations:

public static func parse(_ raw: RawSpan) throws -> PacketHeader {
  guard raw.byteCount >= PacketHeader.byteCount else {
    throw PacketParseError.truncated(expected: PacketHeader.byteCount, got: raw.byteCount)
  }
  let magic = UInt16(
    bigEndian: raw.unsafeLoadUnaligned(fromByteOffset: 0, as: UInt16.self))
  let version = raw.unsafeLoad(fromByteOffset: 2, as: UInt8.self)
  let flags = raw.unsafeLoad(fromByteOffset: 3, as: UInt8.self)
  let length = UInt32(
    bigEndian: raw.unsafeLoadUnaligned(fromByteOffset: 4, as: UInt32.self))
  let checksum = UInt16(
    bigEndian: raw.unsafeLoadUnaligned(fromByteOffset: 8, as: UInt16.self))
  guard magic == magicNumber else { throw PacketParseError.badMagic(magic) }
  return PacketHeader(
    magic: magic, version: version, flags: flags, length: length, checksum: checksum)
}
Enter fullscreen mode Exit fullscreen mode

Note unsafeLoadUnaligned — wire formats make no alignment promises, and this reads the field without a trap. The bytes are never copied into an intermediate [UInt8]; the header is read in place from the caller's buffer, and the RawSpan can't outlive that buffer. This is the code I used to write with a pointer and a nagging worry; now the worry is the compiler's.

Performance notes

My expectation going in was that Span would match UnsafeBufferPointer and InlineArray would beat a heap Array for small fixed sizes. The package ships a small timing harness (Benchmarks/) comparing all three. I'd encourage you to run it on real macOS 26 hardware rather than trust my numbers — but the shape is what you'd predict: Span iteration lowers to the same loop as the unsafe buffer (the bounds checks hoist cleanly over span.indices), and InlineArray avoids the allocation and retain/release traffic that dominates small-Array churn. Span is a performance-neutral safety upgrade; InlineArray is an actual win when the size is known. As always: measure your workload, not my toy.

The comparison, at a glance

UnsafeBufferPointer Span / RawSpan InlineArray<N, T>
Memory safety None — you track validity Compiler-enforced borrow Bounds-checked value type
Bounds checking No Yes Yes
Allocation Views existing storage Views existing storage Inline (stack / enclosing struct)
Escapable? Yes (that's the danger) No (~Escapable) Yes (it's a plain value)
Mutation Via mutable pointer MutableSpan (exclusive) inout / mutating
Availability Always Back-deployed with Swift 6.2 (macOS 10.14.4 / iOS 12.2+) macOS 26 / iOS 26 runtime only

Pitfalls and limitations

A few things to go in with your eyes open:

  • Availability differs by type. Span and RawSpan are back-deployed: build with the Swift 6.2 toolchain and they work down to macOS 10.14.4 / iOS 12.2, because the toolchain ships a compatibility library (libswiftCompatibilitySpan) for older OSes. Watch for that library in bundle or plugin targets, where some people hit "Library not loaded: @rpath/libswiftCompatibilitySpan.dylib". InlineArray is different: it needs runtime support that only exists in macOS 26 / iOS 26, so on older OSes it has to be @available-gated.
  • InlineArray isn't a collection. No Sequence/Collection conformance, so no for-in, map or reduce directly on it. Go through indices or its span.
  • @_lifetime is experimental. As above — the attribute is underscored and flag-gated in 6.2. Fine for your own code behind the flag; risky to expose in a public API you don't want to churn.
  • consume is a new habit. MutableSpan's exclusive borrow means you sometimes end it explicitly. The error messages are good, but it's a muscle you have to build.
  • unsafeLoad is still unsafe. RawSpan makes the buffer safe; the per-field type assertion is still yours to get right. Unaligned loads need unsafeLoadUnaligned.
  • Non-escapable values don't compose like normal values yet. You can't stash a Span in an array, capture one in an escaping closure, or return one without a lifetime annotation. That's the point, but it does mean some patterns need restructuring rather than a drop-in swap.

Migration tips

  • Start at the leaves: swap withUnsafeBufferPointer { … } read loops for a span and delete the closure. It's the lowest-risk change and immediately removes an escape hatch.
  • For parsers, move the [UInt8]-copy step out and read from RawSpan in place.
  • Reach for InlineArray wherever you have a let-sized scratch buffer or a small fixed record — ring buffers, headers, lookup tables, SIMD-ish lanes.
  • Keep your own ~Escapable types internal until the lifetime attribute finalizes.
  • Span-based code back-deploys, so you can adopt it without raising your deployment target. Only InlineArray needs @available(macOS 26, iOS 26, *) gating, with a heap Array or tuple fallback for older OSes.

Open questions for the thread

  1. Lifetime annotations in public API — are people shipping ~Escapable types across module boundaries yet, given @_lifetime is still experimental? How are you insulating callers from the expected rename?
  2. InlineArray ergonomics at larger N — the closure initializer is nice for small sizes, but is anyone using InlineArray for genuinely large fixed buffers, and how does codegen hold up versus a heap Array there?
  3. Interop — what's your approach to handing a Span/RawSpan across a C or Objective-C boundary without falling back to raw pointers and losing the guarantee?

I'd love to hear where these have worked for you — and where they've fought back. The code for everything above is in the SpanPlayground package; corrections welcome.

Top comments (1)

Collapse
 
prikshit profile image
Prikshit •

The point that InlineArray isn't a Sequence is the one I'd have tripped over, since for in is muscle memory. Does going through table.span give you a clean loop in practice, or do you end up writing index loops everywhere? Also curious whether @_lifetime(borrow base) on ByteView can stop someone passing a pointer that escaped from a withUnsafe closure.