skip to content

What do Swift 6.2's Span and MutableSpan give you over withUnsafeBytes, and why can't a function return the Span of a local array?

level: middleimportance: nice to knowfreq 15%

answer

  1. a view, not an owner
  2. ~Escapable keeps it in scope
  3. bounds-checked subscript
  4. a span holds an access

basics

~20 s

Span is a bounds-checked, non-owning view of contiguous memory that is ~Escapable, so the compiler keeps it inside the lifetime of its source; MutableSpan adds in-place writes. Returning a local array's span would outlive the array, so Swift 6.4 rejects it.

solid answer

~50 s

Since Swift 6.2, `Span<Element>` is a non-owning view of initialized contiguous memory, obtained from properties such as `array.span`. Unlike the pointer in `withUnsafeBytes`, its subscript is **bounds-checked** (it traps with `Index out of bounds` in `-O` builds too), and the type is **`~Escapable`**: the compiler ties its lifetime to the container it came from. That is why `func headerSpan() -> Span<UInt8>` returning a local array's `span` is rejected (`a function cannot return a ~Escapable result`), and why a span cannot be a class's stored property or be captured by an escaping closure. A live span also holds a read access to its array, so appending to the array while the span is used is an exclusivity error. `MutableSpan`, from `array.mutableSpan`, is `~Copyable` and `~Escapable`, allows element writes and `swapAt(_:_:)`, and holds exclusive access while it lives.

code

swift · 17 lines
swift
func checksum(_ bytes: Span<UInt8>) -> UInt32 {
    var sum: UInt32 = 0
    for i in bytes.indices {
        sum &+= UInt32(bytes[i])
    }
    return sum
}

func bigEndianUInt16(_ bytes: Span<UInt8>, at offset: Int) -> UInt16 {
    UInt16(bytes[offset]) << 8 | UInt16(bytes[offset + 1])
}

let file: [UInt8] = [0x4B, 0x41, 0x54, 0x41, 0x00, 0x02, 0x00, 0x00, 0x01, 0x00]
let span = file.span
print(checksum(span), bigEndianUInt16(span, at: 4))
let header = span.extracting(0..<4)
print(header.count)

go deeper

for a junior

Remember that Span is a read-only view of an array's storage that cannot leave the scope it was made in, and that MutableSpan is the writable form.

for a middle

Explain ~Escapable, the errors for returning or storing a span, and why a live span holds an access to its array.

for a senior

Choose Span parameters for parser helpers instead of unsafe pointers, and know which operations are still unchecked or @unsafe in 6.4.

for a principal

Weigh adopting Span against deployment targets and the still-experimental lifetime annotations before making it a public API currency type.

## The problem Span solves Before Swift 6.2, the fast way to read an array's bytes was `withUnsafeBytes`, which lends a closure an `UnsafeRawBufferPointer`. That pointer is unsafe in three ways: it is not bounds-checked in release builds, the compiler does not stop it escaping the closure, and every helper the closure calls must also be written against unsafe pointers. **`Span<Element>`** (SE-0447, Swift 6.2) is the safe replacement for that local processing. The standard library describes it as *a non-owning, non-escaping view into memory* that *inherits the lifetime of the container owning the contiguous memory*, with operations that are *bounds-checked*. ## What a span gives you - **No copy.** `array.span` is O(1) for a native array; the span borrows the existing storage. - **Bounds checks that stay in release builds.** `span[i]` checks `i` with a precondition, so an out-of-range index traps with `Index out of bounds` in `-O` builds too. `subscript(unchecked:)` skips the check and is marked `@unsafe`. - **Lifetime checked at compile time.** `Span` is **`~Escapable`** (SE-0446). The compiler tracks which value it depends on and rejects any use that would outlive that value. - **Safe helper signatures.** A function can take `Span<UInt8>` as a parameter, so a parser's helpers no longer need pointers at all. ```swift func checksum(_ bytes: Span<UInt8>) -> UInt32 { var sum: UInt32 = 0 for i in bytes.indices { sum &+= UInt32(bytes[i]) } return sum } let total = checksum(file.span) ``` `Span` is **not a `Collection`**: the collection protocols assume copyable, escapable values. It offers `count`, `isEmpty`, `indices`, the subscript and `extracting(_:)` for a sub-span. ## Why a function cannot return a local array's span ```swift func headerSpan() -> Span<UInt8> { let file: [UInt8] = [0x4B, 0x41, 0x54, 0x41] return file.span // error: a function cannot return a ~Escapable result } ``` The span depends on `file`, which is destroyed when the function returns, so the result would dangle. In Swift 6.4 an ordinary function cannot return a `~Escapable` value at all: stating which argument the result depends on needs lifetime-dependence annotations that are still an **experimental feature**. The same rule produces these errors: | Attempt | Swift 6.4 diagnostic | |---|---| | return `file.span` from a function | `a function cannot return a ~Escapable result` | | store a `Span` in a class property | `the 'get' accessor cannot return a ~Escapable result` | | capture a span in a closure that is returned | `lifetime-dependent variable 's' escapes its scope` | | append to the array while its span is in use | `overlapping accesses to 'samples', but modification requires exclusive access` | ## Spans and exclusivity The last row is the link to the **law of exclusivity**. While a span is alive it holds a **read access** to its source, so a mutation of that array in the meantime is an overlapping access, reported at compile time. **`MutableSpan<Element>`** (SE-0467, Swift 6.2) is the writable counterpart: 1. Get it with `var view = bodies.mutableSpan` — O(1) when the array's storage is uniquely referenced, O(n) otherwise, because it first makes the storage unique. 2. Write elements in place with `view[i] = …` or `view.swapAt(i, j)`. 3. While `view` is in use it holds **exclusive (modify) access** to `bodies`; even reading `bodies.count` in that window is an overlapping-access error. `MutableSpan` is both **`~Copyable`** and `~Escapable`, so there is only ever one of it for a given array at a time. ## Limits to know - Spans are a local-processing tool: store the array, not the span. - Swift 6.4 marked `Span.bytes` and `MutableSpan.mutableBytes` `@unsafe`, because padding bytes in some element types may be uninitialized. - Ownership of `~Copyable` values in general — `borrowing`, `consuming`, `consume` — is covered with noncopyable types.

  • Why is Swift's MutableSpan ~Copyable when Span is Copyable?
    Copies of a `Span` are harmless: they are all read-only views of storage that is only being read. Two copies of a `MutableSpan` would be two writable views of the same memory at once, which breaks exclusive access. Making it `~Copyable` keeps a single writer, matching the modify access it holds on the array.
  • Does a Swift Span check its index in release builds?
    Yes. The subscript validates the index with a precondition, which `-O` keeps, so `span[12]` on a ten-element span traps with `Index out of bounds`. Only `subscript(unchecked:)`, which is marked `@unsafe`, skips the check.

A span is like a reading-room pass for a library book: you can read the book only inside the room, and the library will not let the book be withdrawn or rewritten while any pass for it is still out.

  • Span copies the array's elements into a new buffer.
  • A Span can be stored in a class property to cache a view of an array.
  • Span's subscript is unchecked in -O builds like an unsafe buffer pointer.
  • MutableSpan lets several writers update the same array at once.
  • Span conforms to Collection, so map and filter work on it directly.

Assumes Swift 6.2 or later: Span (SE-0447), MutableSpan (SE-0467) and ~Escapable (SE-0446) shipped in 6.2; declaring your own lifetime dependencies is still experimental in 6.4.