skip to content

Exclusivity and Unsafe Pointers

Swift forbids overlapping writes to one variable and checks it at compile or run time, while unsafe pointers opt out. Interviewers ask why a simultaneous access error appears.

on this pageshow

explore

questions

6

What does Swift's law of exclusivity forbid, and when do two accesses to the same variable conflict?

level: juniorimportance: should knowfreq 30%

answer

  1. not about threads
  2. location, write, duration
  3. long-term: inout and mutating self
  4. copy into a local first

basics

~20 s

Swift 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 s

The 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 lines
swift
func 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

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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.
open as a page

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%

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.

open as a page

A Swift app traps with 'Simultaneous accesses to …, but modification requires exclusive access' — why wasn't this a compile error, and how do you fix it?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Class stored properties, globals and escaping-captured variables are checked at run time because the compiler cannot see every access to them; from Swift 5 on, that check traps in release builds too. Finish the read before the long write starts.

open as a page

In a Swift binary parser, why is returning raw.baseAddress from bytes.withUnsafeBytes and reading the header later a bug, and how should the header be read?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The buffer pointer that Array.withUnsafeBytes passes in is valid only while the closure runs, so a pointer returned from it dangles. Do every read inside the closure and return plain values, using loadUnaligned for packed fields.

open as a page

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%

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.

open as a page

What does Swift 6.2's -strict-memory-safety flag report, and what do the unsafe expression and the @unsafe and @safe attributes do?

level: seniorimportance: nice to knowfreq 8%

basics

~20 s

Since Swift 6.2, -strict-memory-safety adds warnings wherever code uses unsafe constructs such as Unsafe pointer types, unowned(unsafe) or unsafeBitCast. Mark each use with an unsafe expression, mark unsafe APIs @unsafe, or declare a type @safe when it hides unsafe storage.

open as a page