What does Swift's law of exclusivity forbid, and when do two accesses to the same variable conflict?
answer
- not about threads
- location, write, duration
- long-term: inout and mutating self
- copy into a local first
basics
~20 sSwift forbids modifying a variable while another access to it is in progress: two accesses conflict when they hit the same location, are not both reads (or both atomic) and overlap in time. Violations are compile errors or run-time traps.
solid answer
~50 sThe law of exclusivity says a write needs exclusive access: no other read or write of the same variable may overlap it. Two accesses conflict when they hit the same memory location, they are not both reads (and not both atomic), and their durations overlap. Most accesses are instantaneous, so nothing can run in between; the long-term ones are an `inout` argument, which holds write access for the whole call, and `self` inside a `mutating` method. The classic conflict is a closure that reads a variable while a function is changing that same variable through `inout`. Swift reports it as `overlapping accesses to 'x', but modification requires exclusive access` at compile time, or traps at run time when it cannot prove the conflict statically. The usual fix is to copy the value into a local before the long access starts.
code
swift · 10 linesfunc applyTwice(_ value: inout Double, _ change: (inout Double) -> Void) {
change(&value)
change(&value)
}
func simulate() {
var speed = 2.0
applyTwice(&speed) { $0 += speed } // reads speed during the inout write
print(speed)
}go deeper
Recall the three conditions, same location, at least one write and overlapping durations, and that copying the value into a local before the call is the usual fix.
Explain instantaneous versus long-term accesses: an inout argument holds write access for the whole call and a mutating method holds it on self, which is where every overlap comes from.
Say which variables the compiler checks statically and which it leaves to run-time checks, class stored properties, globals and escaping captures, and connect a crash's trap message back to the rule.
Frame the rule as the guarantee that lets the optimizer treat inout values as unaliased, and treat unsafe pointers as the places where a team takes that guarantee back by hand.
## What the rule says Swift's **law of exclusivity** (introduced by Swift Evolution proposal SE-0176) states that a variable may not be accessed by two overlapping accesses unless both of them are reads. In practice: **modifying a variable requires exclusive access to it**. "Variable" here means any mutable memory — a local `var`, a global, a stored property of a struct or class, an `inout` parameter. The rule exists for two reasons. It keeps Swift memory-safe when a value is being changed in several steps, and it lets the optimizer assume that an `inout` argument is not aliased by something else the function can reach. It is **not** a rule about threads. The Swift book is explicit that these conflicts happen on a single thread, in ordinary sequential code. Races between threads are a separate problem, handled by data-race checking in the Swift 6 language mode and by Thread Sanitizer. ## The three conditions for a conflict Two accesses conflict only when all of these hold: 1. **They are not both reads**, and not both atomic operations (calls on the Synchronization module's `Atomic` type or C atomics). 2. **They access the same location in memory** — the same variable, constant or property. 3. **Their durations overlap.** Drop any one of the three and there is no conflict. Two overlapping reads are fine; two overlapping writes to *different* variables are fine; a read that finishes before the write begins is fine. ## Instantaneous and long-term accesses Condition 3 depends on how long each access lasts. - An **instantaneous** access cannot have other code run between its start and its end. Reading a variable to pass it by value, or assigning a new value, is instantaneous. Two instantaneous accesses can never overlap. - A **long-term** access lets other code run while it is open. The book names two main sources: an **`inout` argument**, whose write access starts after the other arguments are evaluated and lasts for the entire call, and **`self` in a `mutating` method**, which is under write access for the whole method. Every conflict you meet in practice involves at least one long-term access. ## A conflict in code ```swift func applyTwice(_ value: inout Double, _ change: (inout Double) -> Void) { change(&value) change(&value) } func simulate() { var speed = 2.0 applyTwice(&speed) { $0 += speed } // error } ``` `applyTwice` holds a write access to `speed` for the whole call. The closure reads `speed` by name while that write is open, so the compiler reports: `overlapping accesses to 'speed', but modification requires exclusive access; consider copying to a local variable` The fix is the one the diagnostic suggests — read first, then start the long access: ```swift let boost = speed applyTwice(&speed) { $0 += boost } // speed ends at 6.0 ``` Now the read of `speed` ends before the write begins, and `boost` is a different location. ## Compile time or run time Swift enforces the rule as strongly as it can for each kind of variable: - **Local variables and `inout` parameters**, including the struct values they hold, are checked **statically**: the compiler sees every access and emits the error above. - **Class stored properties, global variables and variables captured by escaping closures** are checked **dynamically**: the runtime tracks open accesses and traps with `Simultaneous accesses to …, but modification requires exclusive access`. - **`let` constants** need no enforcement, since every access is a read. - **Unsafe pointers** get no enforcement at all; keeping them exclusive is the programmer's job. ## What it is not | Question | Answer | |---|---| | Is it a data race? | No — it happens within one thread of execution | | Do two reads conflict? | No — at least one access must write | | Is every violation a compile error? | No — some are run-time traps | How `inout` copies a value in and out is covered with function parameters; exclusivity is only about overlapping accesses to one location.
- Do two overlapping reads of the same Swift variable violate exclusivity?No. A conflict needs at least one of the two accesses to be a write, and the pair must not both be atomic. Any number of overlapping reads is allowed, which is also why a `let` constant needs no enforcement at all: every access to it is a read.
- Is an exclusivity violation the same thing as a data race in Swift?No. Exclusivity conflicts happen within one thread: a closure reads a variable while an `inout` call on the same thread is still writing it. The book guarantees a compile-time or run-time error for those. Races between threads are a separate problem, caught by the Swift 6 language mode's data-race checks and by Thread Sanitizer.
It is like a budget written on paper in the middle of an update: while items are being added and the total is not yet fixed, anyone reading the total gets a wrong number. Swift's rule is that nobody reads or writes the sheet while one edit is open; two people only reading it at once is fine.
- Exclusivity violations can only happen in multithreaded code.
- Two overlapping reads of the same variable break the law of exclusivity.
- Every exclusivity violation is caught at compile time.
- Passing a variable inout still lets a closure read it by name during the call.