skip to content

Why does a Swift struct's `mutating` method fail to compile when it passes a closure that captures `self` to `DispatchQueue.main.async`, and how do you fix it?

level: seniorimportance: should knowfreq 35%

answer

  1. write access ends with the call
  2. escaping outlives the method
  3. copy-in copy-out model
  4. capture a copy or go async

basics

~20 s

A mutating method has write access to self only until it returns, but an escaping closure may run later, so Swift rejects the capture. Capture an immutable copy, hand the result to the owner, or make the method async.

solid answer

~50 s

In a `mutating` method `self` behaves like an `inout` parameter: the method has write access to the caller's value only until it returns, and the result is written back then. `DispatchQueue.main.async` takes an escaping closure that may run later, when that access has ended and the variable may hold a different value or no longer exist, so the compiler reports "escaping closure captures mutating 'self' parameter". Non-escaping closures such as `forEach`'s are fine because they finish inside the call. Fixes depend on intent: capture `[self]` or the needed values when the closure only reads; return the result through a completion handler and let the owner of the `var` assign it; or write `mutating func reload() async` and `await` the work, so the write-back happens when the call ends. `[weak self]` is not a fix: `weak` applies only to class references.

code

swift · 11 lines
swift
import Dispatch

struct Feed {
    var items: [String] = []

    mutating func reloadLater() {
        DispatchQueue.main.async {
            self.items = ["fresh"]
        }
    }
}

go deeper

for a junior

Recall that a struct's mutating method cannot hand self to a closure that runs later, such as a DispatchQueue.main.async block.

for a middle

Explain that mutating self behaves like inout with write access only for the call, and that only escaping closures are rejected.

for a senior

Choose the fix by intent: read-only capture, a completion handler to the owner, or an async mutating method, and spot the local-copy version that silently loses updates.

for a principal

Read repeated escaping updates of a struct as a modelling signal: identity and shared mutable state belong in a class or actor, not a value type.

## The error A struct method that schedules work for later and updates its own state is a common first attempt: ```swift mutating func reloadLater() { DispatchQueue.main.async { self.items = ["fresh"] } } ``` The compiler rejects it in both language modes with `escaping closure captures mutating 'self' parameter`, pointing at the closure and at the use of `self` inside it. The error is reported during the compiler's later checking passes, so a quick `-typecheck` run may not show it; a full build does. ## Why Swift refuses A `mutating` method has **write access to `self` for the duration of the method call** — the Swift book's wording in its chapter on memory safety. It behaves like an `inout` parameter — the compiler's diagnostic calls it the mutating `self` parameter — so the model is **copy-in copy-out**: the caller's value is copied in, the method changes the copy, and the copy is assigned back when the method returns. The compiler may optimise this into direct access to the caller's memory, but correct code must work under either model. An **escaping closure** is one that may be called after the function it was passed to has returned. `DispatchQueue.main.async` stores the closure and runs it later. By then: - the mutating call has ended, and its write-back has already happened; - the caller's variable may have been reassigned, copied elsewhere, or gone out of scope; - there is no single place left that "self" could still mean. Allowing the capture would mean either silently losing the write or writing into memory that no longer belongs to that variable. The Swift reference states the general rule for in-out parameters: a closure or nested function that captures one must be nonescaping. `self` in a mutating method falls under the same rule. **Non-escaping closures are fine.** `items.forEach { _ in self.count += 1 }` compiles, because `forEach` calls its closure before returning, while the method still holds write access. ## Fixes, by what you actually need 1. **The closure only reads the value.** Capture an immutable copy with a capture list — `{ [self] in print(self.items) }` — or capture just the values needed. Inside, `self` is a frozen copy taken when the closure was created; trying to assign to it reports `cannot assign to property: 'self' is an immutable capture`. 2. **The work produces a new value for the owner.** Make the method non-mutating, take a completion handler, and let the code that owns the `var` (often a class-based view model or controller) assign the result. The struct stays a plain value; the owner decides where the update lands. 3. **The update can be awaited.** Write `mutating func reload() async` and `await` the work inside it. The method keeps write access across the suspension and writes back when it returns, so `items = await fetchItems()` is legal. The caller must hold the value in a `var` and `await feed.reload()`. 4. **The state really must be shared and updated later by whoever holds it.** Then you want a reference type — a class or an actor — rather than a struct; choosing between value and reference types is covered in the material on copy semantics. ## Fixes that do not work | Attempt | Result | |---|---| | `[weak self]` in the capture list | rejected: `'weak' may only be applied to class and class-bound protocol types, not 'Feed'` | | `[self]` and then assigning `self.items` | rejected: `self` is an immutable capture | | Removing `mutating` | `self` becomes immutable, so the assignment inside the closure still fails | | Copying into a local `var` and mutating the copy in the closure | compiles, but the caller's value never sees the change | The last row is the dangerous one: it builds, and the update silently disappears. If you capture a local copy, you must also deliver its final value back to whoever owns the original. ## What to look for in review - A mutating method that starts asynchronous work with a callback API is a design smell; ask who should receive the result. - An `async` mutating method holds exclusive access to the value until it returns, including while suspended; another access to the same variable during that time can be an exclusivity conflict. - A struct that keeps needing escaping updates of itself is usually modelling an object with identity, which is a class's job.

  • Why does `items.forEach { _ in self.count += 1 }` compile inside the same mutating method?
    `forEach` takes a non-escaping closure, which the compiler knows runs before `forEach` returns, while the mutating method still holds write access to `self`. Only closures that may outlive the method are rejected, because they could run after the write-back.
  • Why does copying `self` into a local `var` and mutating that copy inside the escaping closure not solve the problem?
    It compiles, because the closure now captures an ordinary local variable. But the copy is independent of the caller's value, so the change made later never reaches it. Unless the closure also hands the copy back to the owner, the update is silently lost.

  • Suggests [weak self] to break the capture inside a struct method
  • Says marking the closure parameter @escaping fixes the error
  • Believes non-escaping closures in a mutating method are rejected too
  • Thinks the closure captures a live reference to the caller's struct variable
  • Claims copying self into a local var keeps the original updated