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

**URL:** <https://forums.swift.org/t/span-inlinearray-and-escapable-in-practice-safe-low-level-memory-in-swift-6-2/91257>\
**Category:** Community Showcase\
**Created:** [December 1, 2026, 5:02am UTC](https://forums.swift.org/t/span-inlinearray-and-escapable-in-practice-safe-low-level-memory-in-swift-6-2/91257 "2026-12-01T05:02:08Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dheerendra](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dheerendra/32/47241_2.png) [@dheerendra](https://forums.swift.org/u/dheerendra)\
**Post date:** [December 1, 2026, 5:02am UTC](https://forums.swift.org/t/span-inlinearray-and-escapable-in-practice-safe-low-level-memory-in-swift-6-2/91257/1 "2026-12-01T05:02:08Z")

</div>

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_](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0447-span-access-shared-contiguous-storage.md)) 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_](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0456-stdlib-span-properties.md).

```swift
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
}

```

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`:

```swift
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
}

```

`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_](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0467-MutableSpan.md) 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:

```swift
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
}

```

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_](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0453-vector.md)) 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:

```swift
public struct RingBuffer4: Sendable {
  private var storage: InlineArray<4, Int>
  private var head = 0
  private var filled = 0

  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
    }
  }
  // ...
}

```

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:

```swift
public static func squares() -> InlineArray<8, Int> {
  InlineArray<8, Int> { index in index * index }
}

```

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.

## ~Escapable and lifetimes: how it's all sound

Everything above rests on [SE-0446, _Nonescapable Types_](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0446-non-escapable.md). 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_](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0465-nonescapable-stdlib-primitives.md) rounds out the supporting cast.

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

```swift
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]
  }
}

```

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

```swift
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'

```

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:

```swift
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)
}

```

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 (macOS 10.14.4+ / iOS 12.2+) | macOS 26 / iOS 26 stdlib only |

## Pitfalls and limitations

A few things to go in with your eyes open:

- **Availability is split.** `Span` and `RawSpan` are back-deployed: built with the Swift 6.2 toolchain, they run all the way back to macOS 10.14.4 / iOS 12.2 via a compatibility library (`libswiftCompatibilitySpan`) that ships with your app. `InlineArray` is _not_ — it lives in the macOS 26 / iOS 26 standard library, so on older OSes it needs `@available` gating, or you get a `dyld` "Symbol not found" at launch.
- **`@_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.
- Gate `InlineArray` (and anything built on it) behind `@available(macOS 26, iOS 26, *)` if you ship to older OSes; `Span` adoption doesn't need that gate.

## 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.
