InlineArray and Span
suggest changeSwift 6.2 added two standard library types for code where performance matters:
InlineArray<N, Element>is an array with a fixed size. The size is part of the type and the elements are stored inline, without a separate heap allocation. Swift 6.2 also added the shorter spelling[N of Element]. (SE-0453, SE-0452 integer generic parameters, SE-0483 type sugar)Span<Element>is a safe, read-only view of contiguous memory.MutableSpanis the mutable version andRawSpanviews raw bytes. The compiler checks at compile time that a span never outlives the memory it points to. (SE-0447, SE-0456, SE-0467)
Together they cover most of what you used to need unsafe buffer pointers for, without the unsafety.
All examples were compiled and run with Swift 6.4.1 on Windows:
swiftc -swift-version 6 main.swift -o main.exe
InlineArray basics
var rgb: InlineArray<3, UInt8> = [255, 128, 0]
let names: [4 of String] = ["north", "east", "south", "west"]
let primes: [_ of Int] = [2, 3, 5, 7, 11] // count inferred: [5 of Int]
print(rgb.count, names.count, primes.count)
print(names[2])
rgb[1] = 64
rgb.swapAt(0, 2)
for i in rgb.indices {
print(i, rgb[i])
}
let zeros = [8 of Double](repeating: 0)
let squares = [5 of Int] { i in i * i } // closure gets the index
let powers = [6 of Int](first: 1) { $0 * 2 } // each element from the previous
for x in squares { print(x, terminator: " ") }
print()
for x in powers { print(x, terminator: " ") }
print()
print(zeros[7], [4 of Int].count)
Output:
3 4 5
south
0 0
1 64
2 255
0 1 4 9 16
1 2 4 8 16 32
0.0 4
InlineArray<3, UInt8> and [3 of UInt8] are the same type. The first generic argument is an integer, not a type. The size can be inferred with _ from an array literal.
There are four ways to create one:
- an array literal with exactly
Nelements init(repeating:)init(_:)with a closure that gets each index and returns the elementinit(first:next:), which builds each element from the previous one
count is a static property too, so [4 of Int].count is 4 without creating a value.
The size is checked by the compiler
The literal must have exactly as many elements as the type says, and arrays of different sizes are different types:
let a: [3 of Int] = [1, 2, 3, 4]
// error: expected '3' elements in inline array literal, but got '4'
let b: [3 of Int] = [1, 2, 3]
let c: [4 of Int] = b
// error: cannot assign value of type '[3 of Int]' to type '[4 of Int]'
An out-of-range index can't be caught at compile time in general, so it traps at runtime, just like Array:
Swift/InlineArray.swift:492: Fatal error: Index out of bounds
What InlineArray is not
InlineArray has a deliberately small API. It's not a smaller Array:
- No
append,removeorinsert. The size never changes. - It doesn't conform to
SequenceorCollection, somap,filter,contains,sortedand so on are missing.a.map { $0 }giveserror: value of type '[3 of Int]' has no member 'map'. With the 6.4 compiler a plainfor x in aloop works, as shown above. To be portable to older 6.x compilers, loop overa.indices. - It's not
EquatableorHashable.a == bgiveserror: binary operator '==' cannot be applied to two '[3 of Int]' operands. print(a)isn't useful. It printsInlineArray<4, Int>(_storage: (Unknown)).
The reason is that InlineArray also supports noncopyable elements (see below), and the Sequence / Collection protocols require copyable elements.
Memory layout: no heap allocation
An Array value is one pointer to a reference-counted buffer on the heap. An InlineArray value is the elements:
print(MemoryLayout<[4 of UInt8]>.size)
print(MemoryLayout<[4 of Int]>.size)
print(MemoryLayout<[Int]>.size) // just a reference to heap storage
struct Particle {
var position: [3 of Float]
var velocity: [3 of Float]
}
print(MemoryLayout<Particle>.size)
Output:
4
32
8
24
Particle is 24 bytes: 6 floats stored directly in the struct. With [Float] it would hold two references to two separate heap buffers. Copying it would mean reference counting, and changing it would mean a uniqueness check and maybe a copy.
This matters most for many small values: points, colors, matrices, hash digests, fixed-size headers, small lookup tables. It also helps when a local array lives on the stack in a hot loop. For a general background on stack vs heap see Allocation Performance.
A rough measurement
This program creates 10 million small values with a 3-element Array and with a [3 of Double]:
struct PointA { var c: [Double] } // heap-allocated storage
struct PointI { var c: [3 of Double] } // inline storage
@inline(never)
func makeA(_ i: Int) -> PointA {
let d = Double(i)
return PointA(c: [d, d + 1, d + 2])
}
@inline(never)
func makeI(_ i: Int) -> PointI {
let d = Double(i)
return PointI(c: [d, d + 1, d + 2])
}
let n = 10_000_000
let clock = ContinuousClock()
var total = 0.0
let tA = clock.measure {
for i in 0..<n { total += makeA(i).c[1] }
}
let tI = clock.measure {
for i in 0..<n { total += makeI(i).c[1] }
}
print("Array: ", tA)
print("InlineArray: ", tI)
print(total > 0)
print(MemoryLayout<PointA>.size, MemoryLayout<PointI>.size)
Compiled with swiftc -O, one run printed:
Array: 0.8332941 seconds
InlineArray: 0.0249244 seconds
true
8 24
Absolute numbers depend on the machine, and a second run gave a somewhat different ratio. The difference comes almost entirely from skipping malloc / free and reference counting. Treat it as an illustration, not a benchmark. Measure your own code.
Copying and noncopyable elements
InlineArray is a value type without copy-on-write. Assigning it copies all elements at once. That's cheap for a few Ints and expensive for [1000 of Double], so keep big inline arrays out of code that copies values around a lot.
Unlike Array, it can hold noncopyable values (see Noncopyable types and ownership):
var a: [3 of Int] = [1, 2, 3]
var b = a // copies all 3 elements now
b[0] = 100
print(a[0], b[0])
struct Handle: ~Copyable {
let id: Int
deinit { print("close", id) }
}
func demo() {
var handles: [2 of Handle] = [Handle(id: 1), Handle(id: 2)]
print("first:", handles[0].id)
handles[1] = Handle(id: 3) // old Handle 2 is destroyed
print("end of demo")
}
demo()
Output:
1 100
first: 1
close 2
end of demo
close 1
close 3
An InlineArray of noncopyable elements is itself noncopyable. let other = handles moves the array instead of copying it, and using handles after that gives error: 'handles' used after consume.
Integer generic parameters
The N in InlineArray<N, Element> is an integer generic parameter. You can declare your own with let, and use them both as a type argument and as a value:
struct Matrix<let Rows: Int, let Columns: Int> {
var storage: [Rows of [Columns of Double]]
init(repeating value: Double) {
storage = .init(repeating: .init(repeating: value))
}
subscript(r: Int, c: Int) -> Double {
get { storage[r][c] }
set { storage[r][c] = newValue }
}
func transposed() -> Matrix<Columns, Rows> {
var t = Matrix<Columns, Rows>(repeating: 0)
for r in 0..<Rows {
for c in 0..<Columns {
t[c, r] = self[r, c]
}
}
return t
}
func printRows() {
for r in 0..<Rows {
var line: [String] = []
for c in 0..<Columns { line.append("\(self[r, c])") }
print(line.joined(separator: " "))
}
}
}
var m = Matrix<2, 3>(repeating: 0)
for r in 0..<2 { for c in 0..<3 { m[r, c] = Double(r * 3 + c) } }
m.printRows()
print("--")
let t = m.transposed()
t.printRows()
print(type(of: t), MemoryLayout<Matrix<2, 3>>.size)
Output:
0.0 1.0 2.0
3.0 4.0 5.0
--
0.0 3.0
1.0 4.0
2.0 5.0
Matrix<3, 2> 48
The return type Matrix<Columns, Rows> states in the type system that transposing swaps the dimensions. Passing a Matrix<3, 2> where a Matrix<2, 3> is expected doesn't compile. The whole 2x3 matrix is 48 bytes (6 doubles) with no heap allocation.
You can't do arithmetic on integer generic parameters (no [Rows * Columns of Double]), so the example nests two inline arrays.
Span: a safe view of contiguous memory
Before Swift 6.2, a function that wanted to read elements stored contiguously, no matter which container they live in, had two options. It could be generic over Collection, which is slower and doesn't promise contiguous memory. Or it could take an UnsafeBufferPointer and make every caller use withUnsafeBufferPointer { }.
Span<Element> gives you the speed of the pointer without the danger. Many types now have a span property:
import Foundation
func average(_ values: Span<Double>) -> Double {
if values.isEmpty { return 0 }
var sum = 0.0
for i in values.indices {
sum += values[i]
}
return sum / Double(values.count)
}
func main() {
let array = [1.0, 2.0, 3.0, 4.0]
let inline: [3 of Double] = [10, 20, 30]
let contiguous = ContiguousArray<Double>([5, 7])
let slice = array[1...]
print(average(array.span))
print(average(inline.span))
print(average(contiguous.span))
print(average(slice.span))
print(average(array.span.extracting(first: 2)))
let text = "héllo"
let utf8 = text.utf8.span // Span<UInt8>
print(utf8.count, utf8[1], utf8[2])
let data = Data([0xCA, 0xFE, 0xBA, 0xBE])
print(data.span.count, String(data.span[0], radix: 16))
}
main()
Output:
2.5
20.0
6.0
3.0
1.5
6 195 169
4 ca
One non-generic function works with Array, ContiguousArray, ArraySlice, InlineArray, a String's UTF-8 bytes and Foundation's Data. Getting .span doesn't copy anything. It's a pointer plus a count.
extracting(_:) takes a sub-span by range. extracting(first:), extracting(last:) and extracting(droppingFirst:) work like prefix and dropFirst on collections. Every subscript is bounds-checked:
Swift/Span.swift:445: Fatal error: Index out of bounds
Like InlineArray, Span isn't a Sequence. Loop over span.indices. for x in span doesn't compile in 6.4.
Why a Span can't escape
Span is a non-escapable type (~Escapable, SE-0446). Its value depends on the lifetime of the container it came from, and the compiler won't let it outlive that container. These are the errors that rule out dangling pointers:
func firstTwo(_ values: [Int]) -> Span<Int> {
return values.span.extracting(first: 2)
}
// error: a function cannot return a ~Escapable result
struct Reader {
var bytes: Span<UInt8>
}
// error: stored property 'bytes' of 'Escapable'-conforming struct 'Reader'
// has non-Escapable type 'Span<UInt8>'
func run(_ values: [Int]) {
let span = values.span
let task: () -> Int = { span.count }
// error: lifetime-dependent variable 'span' escapes its scope
print(task())
}
Exclusivity checking also stops the container from being changed while a span into it is alive, so a reallocation can't leave the span pointing at freed memory:
func run() {
var values = [1, 2, 3]
let span = values.span
values.append(4)
// error: overlapping accesses to 'values', but modification
// requires exclusive access
print(span.count)
}
With the 6.4 compiler, a span stored in a local let keeps the read access open until the end of its scope. Moving print(span.count) above append is not enough, and still gives the same error. End the span's scope first:
func run() {
var values = [1, 2, 3]
do {
let span = values.span
print(span.count)
}
values.append(4) // fine: the span is gone
print(values)
print(values.span.count) // a temporary span ends with the statement
}
run()
3
[1, 2, 3, 4]
4
Some top-level code is affected too: let s = a.span on a global var a fails with lifetime-dependent value escapes its scope. Put such code inside a function.
The pattern is: create the span, pass it down to functions that use it, and let it end. A Span parameter is like a borrowed array that the callee can't keep.
Your own types can store a Span only if they are ~Escapable themselves. Their initializers then need lifetime annotations (@_lifetime(copy bytes)), which are still experimental in 6.4 and need -enable-experimental-feature Lifetimes.
RawSpan: viewing bytes
span.bytes gives a RawSpan, a view of the same memory as untyped bytes:
func main() {
let numbers: [UInt32] = [1, 0x0102_0304]
let bytes = numbers.span.bytes // RawSpan over the same memory
print(bytes.byteCount)
var hex: [String] = []
for offset in bytes.byteOffsets {
let b = unsafe bytes.unsafeLoad(fromByteOffset: offset, as: UInt8.self)
hex.append(String(b, radix: 16))
}
print(hex.joined(separator: " "))
let second = bytes.extracting(droppingFirst: 4)
print(second.byteCount, unsafe second.unsafeLoad(as: UInt32.self) == 0x0102_0304)
}
main()
Output (on a little-endian machine):
8
1 0 0 0 4 3 2 1
4 true
Byte offsets are bounds-checked. unsafeLoad(fromByteOffset:as:) is marked unsafe, though, because reinterpreting bytes as an arbitrary type (a class reference, or a misaligned value) can break memory safety. The unsafe keyword in front of it is explained below.
MutableSpan: changing elements in place
mutableSpan gives write access to the elements, but not to the size of the container:
func normalize(_ values: inout MutableSpan<Double>) {
var maxValue = 0.0
for i in values.indices { maxValue = max(maxValue, values[i]) }
guard maxValue > 0 else { return }
for i in values.indices { values[i] /= maxValue }
}
func main() {
var scores = [2.0, 5.0, 10.0]
var span = scores.mutableSpan
normalize(&span)
print(scores)
var fixed: [4 of Double] = [1, 2, 3, 4]
var fixedSpan = fixed.mutableSpan
normalize(&fixedSpan)
fixedSpan.swapAt(0, 3)
for x in fixed { print(x, terminator: " ") }
print()
var shared = [1, 2, 3]
let copy = shared // shares storage with `shared`
var m = shared.mutableSpan // triggers copy-on-write first
m[0] = 99
print(shared, copy)
var buffer = [Int](repeating: 7, count: 5)
var bufSpan = buffer.mutableSpan
bufSpan.update(repeating: 0)
print(buffer)
}
main()
Output:
[0.2, 0.5, 1.0]
1.0 0.5 0.75 0.25
[99, 2, 3] [1, 2, 3]
[0, 0, 0, 0, 0]
Some things to note:
- Take the mutable span into a
varfirst and pass itinout.normalize(&scores.mutableSpan)fails, becausemutableSpanis a get-only property. - Getting
mutableSpanfrom an array whose storage is shared makes the array unique first (copy-on-write), socopyisn't affected. - While a mutable span is alive you can't touch the array at all, not even to read it.
print(scores)works above becausespanisn't used afternormalize.
Replacing withUnsafeBufferPointer
Here is a typical pre-6.2 function written with a buffer pointer:
func checksum(_ data: [UInt8]) -> UInt32 {
data.withUnsafeBufferPointer { buf in
var sum: UInt32 = 0
for i in 0..<buf.count {
sum = sum &* 31 &+ UInt32(buf[i])
}
return sum
}
}
print(checksum([1, 2, 3]))
1026
It only accepts [UInt8], the closure adds noise, and nothing prevents the pointer from leaking out of the closure. The Span version is shorter, just as fast, and works with more container types:
func checksum(_ data: Span<UInt8>) -> UInt32 {
var sum: UInt32 = 0
for i in data.indices {
sum = sum &* 31 &+ UInt32(data[i])
}
return sum
}
func main() {
let bytes: [UInt8] = [1, 2, 3]
let header: [4 of UInt8] = [1, 2, 3, 4]
print(checksum(bytes.span))
print(checksum(header.span.extracting(first: 3)))
}
main()
1026
1026
You still need pointers for C APIs and older Swift APIs that take them. Span has withUnsafeBufferPointer for that, and MutableSpan has withUnsafeMutableBufferPointer. Keep the unsafe part as small as possible:
// An existing API that still takes a pointer, e.g. imported from C.
func legacySum(_ p: UnsafePointer<Int32>, _ count: Int) -> Int32 {
var total: Int32 = 0
for i in 0..<count { total += unsafe p[i] }
return total
}
func sum(_ values: Span<Int32>) -> Int32 {
values.withUnsafeBufferPointer { buf in
unsafe legacySum(buf.baseAddress!, buf.count)
}
}
func main() {
let values: [Int32] = [10, 20, 30]
print(sum(values.span))
}
main()
60
Strict memory safety and the unsafe keyword
Swift 6.2 also added opt-in strict memory safety checking (SE-0458). Compile with -strict-memory-safety and the compiler warns about every use of an unsafe construct that isn't acknowledged with the unsafe keyword. For the buffer-pointer checksum above:
swiftc -swift-version 6 -strict-memory-safety old.swift
old.swift:5:19: warning: expression uses unsafe constructs but is not marked with 'unsafe' [#StrictMemorySafety]
3 | var sum: UInt32 = 0
4 | for i in 0..<buf.count {
5 | sum = sum &* 31 &+ UInt32(buf[i])
| | `- note: reference to parameter 'buf' involves unsafe type 'UnsafeBufferPointer<UInt8>'
| `- warning: expression uses unsafe constructs but is not marked with 'unsafe' [#StrictMemorySafety]
There are two fixes:
- Mark the expression:
UInt32(unsafe buf[i]).unsafeworks liketry. It doesn't change behavior. It marks the place a reviewer should look at. - Rewrite with
Span. TheSpanversion ofchecksumcompiles with no warnings, because span accesses are bounds-checked and lifetime-checked.
The unsafe keyword is accepted without the flag too, which is why the RawSpan and legacySum examples use it. Under -strict-memory-safety the compiler also warns when unsafe is unnecessary: warning: no unsafe operations occur within 'unsafe' expression.
Strict mode is meant for security-sensitive code (parsers, networking, code handling untrusted input). Most apps won't turn it on. For them, Span simply means less unsafe code.
When to use them
Use InlineArray when:
- the number of elements is fixed and known at compile time (coordinates, RGBA, a 4x4 matrix, a SHA-256 digest as
[32 of UInt8]) - you create lots of small values and heap allocation shows up in profiles
- you need a fixed-size collection of noncopyable values
Keep using Array when the size changes, when you need Sequence / Collection algorithms, or when values are big and copied often. Copy-on-write makes copying an Array cheap.
Use Span / MutableSpan / RawSpan:
- as the parameter type of functions that read or update contiguous elements and don't care which container holds them
- instead of
withUnsafeBufferPointer/withUnsafeBytesin pure Swift code - for parsing binary data with bounds-checked byte access
Keep raw pointers only at the boundary with C, wrapped in a small withUnsafeBufferPointer call like legacySum above. The Unsafe Buffer Pointers article describes those pointer types.