In Swift 6.2, how do you build a fixed-size ring buffer of samples on InlineArray, and what changes when its elements are noncopyable?
answer
- count lives in the type
- [8 of Float]
- wrap the index with %
- conditionally Copyable
- build noncopyable elements by index
basics
~20 sStore InlineArray<8, Float>, spelled [8 of Float], keep a write index and wrap it with % count. Copying copies all eight floats eagerly; with a ~Copyable element the InlineArray itself becomes noncopyable and can only move.
solid answer
~40 s`InlineArray<let count: Int, Element: ~Copyable>` puts the count in the type through an integer generic parameter, so `[8 of Float]` is eight floats stored inline, with no separate heap allocation and no `append`. A ring buffer keeps a `next` index, writes `samples[next] = value` and advances with `(next + 1) % samples.count`; an out-of-range subscript traps. Copying a struct that holds it copies every element eagerly, like a tuple. The ownership side is the declaration `extension InlineArray: Copyable where Element: Copyable`: fill it with a `~Copyable` connection type and the whole array is noncopyable, so you build it with the per-index closure initializer rather than `init(repeating:)`, borrow elements through the subscript, and move the array as one value.
code
swift · 29 linesstruct SampleRing {
private var samples: [8 of Float] = .init(repeating: 0) // InlineArray<8, Float>
private var next = 0
private(set) var filled = 0
mutating func record(_ value: Float) {
samples[next] = value
next = (next + 1) % samples.count
filled = min(filled + 1, samples.count)
}
var average: Float {
guard filled > 0 else { return 0 }
var sum: Float = 0
for i in 0..<filled { sum += samples[i] }
return sum / Float(filled)
}
}
func run() {
var live = SampleRing()
for v: Float in [1, 2, 3] { live.record(v) }
var snapshot = live // copies all eight floats eagerly
snapshot.record(100)
print(live.average, snapshot.average)
print(MemoryLayout<SampleRing>.size)
}
run()go deeper
Recall that InlineArray has a fixed count written in its type, such as [8 of Float], and that it has no append.
Walk through the ring-buffer index arithmetic, the eager copy of every element, and the bounds trap on a bad index.
Explain the conditional Copyable conformance and what it changes for a pool of noncopyable connections: per-index construction, borrowed reads, whole-array moves.
Weigh inline fixed storage against Array for hot paths: no allocation versus the cost of copying large inline values in every containing struct.
## A count in the type `InlineArray` arrived in **Swift 6.2** (SE-0453) together with **integer generic parameters** (SE-0452). The standard library declares it as `public struct InlineArray<let count: Int, Element: ~Copyable>: ~Copyable`, and every part of that line matters. - `let count: Int` is a **value** generic parameter: `InlineArray<8, Float>` and `InlineArray<16, Float>` are different types. - The sugar `[8 of Float]` (SE-0483, also Swift 6.2) spells the same type; `[_ of Float]` lets the compiler infer the count from a literal. - The standard library's doc comment states the contract: the type "doesn't use a separate memory allocation just to store its elements", and when a value is copied "all of its elements are copied eagerly, like those of a tuple". - Storage is contiguous. As a stored property of a class it lives in the object's heap allocation; otherwise it is generally on the stack. ## Building the ring buffer A ring buffer of the last eight samples needs no growth, which is exactly what `InlineArray` offers. 1. Declare `private var samples: [8 of Float] = .init(repeating: 0)`. `init(repeating:)` works because `Float` is copyable. 2. Keep `next`, the slot the next write goes to, and `filled`, how many slots hold real data. 3. On `record(_:)`, write `samples[next] = value`, then `next = (next + 1) % samples.count`. 4. Clamp `filled` to `samples.count` so averages ignore unused slots. 5. Read with a plain loop over `0..<filled`; `InlineArray` does not conform to `Sequence` or `Collection`, so `map` and `filter` are not available on it. The subscript is **bounds-checked**: `samples[8] = 1.0` compiles and then stops the program with `Fatal error: Index out of bounds`. The wrap-around is your code's job; the type never wraps for you. `subscript(unchecked:)` skips the check and is memory-unsafe. ## Copy behaviour depends on the element | Element type | Is the `InlineArray` copyable? | What `let b = a` does | |---|---|---| | `Float`, `Int`, any copyable type | yes | copies every element eagerly; no buffer is shared | | a `~Copyable` struct such as a connection | no | moves the whole array; `a` is dead | The first row is the ring-buffer case: `var snapshot = live` produces an independent eight-float copy, so recording into `snapshot` leaves `live` unchanged. How that differs from `Array`'s shared storage is covered with copy-on-write and the collection types; the point here is that nothing is shared. ## Noncopyable elements The second row follows from one line of the standard library, `extension InlineArray: Copyable where Element: Copyable {}`. Without that conformance the type stays `~Copyable`, so: - **Construction** cannot copy one value into every slot. `init(repeating:)` lives in a `where Element: Copyable` extension and fails with `referencing initializer 'init(repeating:)' on 'InlineArray' requires that 'DatabaseConnection' conform to 'Copyable'`. Use `init(_:)`, whose closure receives each index and returns a freshly owned element. - **Reading** `pool[1].handle` borrows the element in place; nothing is copied out. - **Moving** `let owner = pool` transfers all elements at once; a later use of `pool` is `'pool' used after consume`. - **Destruction** runs each element's `deinit` when the owning array's lifetime ends. This is how a fixed pool of connections can be held without a class: `Array` would reject the element type outright. ## Generic over the count Because the count is a generic parameter, a helper can accept any size without losing the static count: `func peak<let n: Int>(_ samples: borrowing InlineArray<n, Float>) -> Float` loops over `samples.indices` and works for `[4 of Float]` and `[8 of Float]` alike. Marking the parameter `borrowing` reads the samples in place instead of handing the function its own copy. In the first example, `MemoryLayout<SampleRing>.size` prints 48: thirty-two bytes of inline floats plus two `Int` fields, with no pointer to a separate buffer. ## Limits to name in an interview - The count is fixed at compile time; there is no `append`, `remove` or resizing. - A large `InlineArray` makes every copy of its containing struct proportionally expensive. - The type is marked available from the Swift 6.2 standard library, so code deploying to older Apple OS releases needs an availability check. - Swift 6.4's `UniqueBox` is the heap-allocated counterpart for a single uniquely owned value; it is not a fixed-size array.
- Why does `InlineArray<3, DatabaseConnection>(repeating:)` fail to compile when the connection is noncopyable?`init(repeating:)` copies one value into every slot, so the standard library declares it only in an extension `where Element: Copyable`; the compiler reports that it requires `DatabaseConnection` to conform to `Copyable`. Use `init(_:)`, whose closure is called once per index and returns a newly created, owned element.
- Where does an InlineArray live when it is a stored property of a Swift class?Inside the class instance's own heap allocation, next to the other stored properties. `InlineArray` never adds a separate allocation for its elements; outside a class it is generally on the stack. So a sample buffer inside a class still costs one object allocation, not two.
- InlineArray grows with append once its fixed count is reached.
- Copying an InlineArray shares one buffer until a write, like Array.
- InlineArray's count is a runtime value passed to its initializer.
- InlineArray can never hold noncopyable elements.
- An InlineArray index past the end wraps around to zero.
Assumes Swift 6.4; InlineArray, integer generic parameters and the [count of Element] spelling arrived in Swift 6.2.