skip to content

Why does Swift reject swap(&bodies[i], &bodies[j]) with an overlapping-access error, and how do you update two array elements instead?

level: middleimportance: should knowfreq 35%

answer

  1. an element access touches the array
  2. two inout writes, one variable
  3. the fix-it names a method
  4. copy out, mutate, write back

basics

~20 s

Passing bodies[i] inout opens a write access to the whole bodies array, so two inout element arguments are two overlapping writes to one variable. Use bodies.swapAt(i, j), or copy both elements into locals, change them and store them back.

solid answer

~40 s

In Swift, accessing part of a value-type variable accesses the whole variable, and an array element passed `inout` goes through the subscript's modify access on `bodies` itself. So `swap(&bodies[i], &bodies[j])` opens two long-term write accesses to `bodies` that overlap, and the compiler reports `overlapping accesses to 'bodies', but modification requires exclusive access; consider calling MutableCollection.swapAt(_:_:)`. `bodies.swapAt(i, j)` is one mutating call, so there is one access, and passing the same index twice is a no-op. The same error hits `bodies[i].collide(with: &bodies[j])`; copy both elements into locals, call the method, and assign them back. A line like `bodies[i].velocity += bodies[j].velocity` is fine, because the read on the right finishes before the write starts.

code

swift · 13 lines
swift
struct Body {
    var position: Double
    var velocity: Double
    mutating func collide(with other: inout Body) {
        swap(&velocity, &other.velocity)
    }
}

func step(_ bodies: inout [Body], _ i: Int, _ j: Int) {
    swap(&bodies[i], &bodies[j])
    bodies[i].collide(with: &bodies[j])
    bodies[i].velocity += bodies[j].velocity
}

go deeper

for a junior

Remember that the compiler suggests swapAt for this exact error, and that copying elements into locals avoids it for other two-element updates.

for a middle

Explain that an element passed inout opens a write access on the whole array through its subscript, so two such arguments are two overlapping writes to one variable.

for a senior

Know the local-struct exception and its three conditions, why a global struct traps at run time instead, and that the diagnostic only appears in a full build, not a typecheck.

for a principal

Use the error as a reading aid in review: two ampersands into one collection in one call is always a conflict, and the shape of the fix shows whether i equal to j was considered.

## The error and where it comes from A physics step often needs to update two bodies stored in the same array. The obvious line does not compile: ```swift swap(&bodies[i], &bodies[j]) // error: overlapping accesses to 'bodies', but modification requires // exclusive access; consider calling MutableCollection.swapAt(_:_:) ``` Swift's **law of exclusivity** forbids two overlapping accesses to the same variable when at least one is a write. The question is why two *different* elements count as the same variable. ## Why an element access touches the whole array Two facts combine: 1. **A part of a value is accessed through the whole value.** The Swift book's rule for structs, tuples and enums is that reading or writing one stored part requires a read or write access to the entire value. An `Array` is a value type too, and its elements are not stored properties of the variable at all. 2. **An element passed `inout` goes through the subscript.** `&bodies[i]` calls the array subscript's modifying accessor on `bodies`, which keeps a **long-term write access** to `bodies` open for the whole call that takes the argument. `swap(_:_:)` takes both arguments `inout`, so the two write accesses to `bodies` are open at the same time. The compiler cannot reason about the indices — and `i` may even equal `j` — so it rejects the call. The fix-it text names the replacement directly. ## Fixes that work - **`swapAt(_:_:)`** — `bodies.swapAt(i, j)` is a single mutating method on `MutableCollection`, so there is exactly one write access. Its documentation states that passing the same index for both arguments has no effect, so the `i == j` case is safe. - **Copy out, mutate, write back** — for any operation that needs two elements as `inout`, such as a `mutating` method that takes another element: ```swift var first = bodies[i] var second = bodies[j] first.collide(with: &second) bodies[i] = first bodies[j] = second ``` Each read and each assignment is instantaneous, so nothing overlaps. - **Read, then write, in one expression** — `bodies[i].velocity += bodies[j].velocity` compiles. The right-hand side is evaluated before the `inout` access for `+=` begins, so the read is already finished. ## The same rule elsewhere The pattern is the same whenever one variable appears twice in one call: | Code | Result | |---|---| | `swap(&bodies[i], &bodies[j])` | compile error, fix-it suggests `swapAt` | | `bodies[i].collide(with: &bodies[j])` | compile error: `self` and the argument both write `bodies` | | `bodies.swapAt(i, j)` | compiles | | `swap(&body.position, &body.velocity)` on a local `var body` | compiles | | the same `swap` on a global `var` | compiles, then traps at run time | The struct-property row is the one exception the book carves out. Overlapping accesses to **different stored properties of a struct** are allowed when the compiler can prove them safe: the properties are stored (not computed), the struct is in a **local** variable (not a global), and it is not captured by an escaping closure. A global struct gets dynamic enforcement instead, so the same `swap` traps with `Simultaneous accesses to …` when it runs. No such exception exists for array elements: elements are not stored properties, so two elements of one array are always one variable to the checker. ## Notes for code review - The error is a SIL diagnostic. `swiftc -typecheck` does not print it; a full build does. - An `inout` element access is a write even if the callee only reads, because the access kind comes from `&`, not from what the function does. - A helper that takes two `inout` elements of one array can usually take the array and two indices instead, which leaves a single access. - `swapAt(_:_:)` is O(1), so it costs nothing over a hand-written swap. How `inout` copies a value in and out at the call boundary is covered with function parameters; this question is only about why two `&` arguments into one array overlap.

  • Why does swap(&body.position, &body.velocity) compile for a local struct but trap for a global one in Swift?
    For a local variable the compiler can prove that two different stored properties never overlap in memory, so it allows the overlapping accesses. A global variable uses dynamic enforcement, and the run-time check tracks the whole variable, so the same call traps with `Simultaneous accesses to …, but modification requires exclusive access`.
  • Does bodies[i].velocity += bodies[j].velocity violate exclusivity in Swift?
    No. The right-hand side is read and finished before the `inout` write access for `+=` begins, so the two accesses to `bodies` never overlap. Only the case where both accesses are open at once, such as two `inout` arguments, is a conflict.

  • Two different indices are two different variables, so swapping them cannot conflict.
  • Checking that i != j before the call makes swap(&bodies[i], &bodies[j]) compile.
  • Struct properties of a global variable get the same exemption as a local one.
  • An inout argument the callee only reads is not a write access.