In Swift 6 language mode, why does awaiting a non-Sendable RequestLog's async method from the main actor fail, and how does nonisolated(nonsending) fix it?
answer
- where a nonisolated async function runs
- the hop off the caller's actor
- self is sent across
- run on the caller's actor
- @concurrent for the old behaviour
basics
~20 sBy default a nonisolated async method runs off the caller's actor, so calling it from the main actor sends the non-Sendable receiver across a boundary. nonisolated(nonsending), from Swift 6.2, runs it on the caller's actor instead, so nothing is sent.
solid answer
~40 sUnless an upcoming feature is enabled, a nonisolated `async` function, including an unannotated async method of an ordinary class, runs on the global concurrent executor, off whatever actor called it. When a `@MainActor` type awaits `log.flush()` on a non-`Sendable` `RequestLog` it owns, the `log` reference would be used on two executors at once, and Swift 6 mode reports "sending 'self.log' risks causing data races". Swift 6.2 (SE-0461) added `nonisolated(nonsending)`: such a function runs on the caller's actor, so its arguments never cross a boundary and the call compiles. `@concurrent` spells the old always-switch behaviour explicitly. The upcoming feature `NonisolatedNonsendingByDefault` makes `nonisolated(nonsending)` the default; it is not on in Swift 6 mode, and its `:migrate` mode adds `@concurrent` to keep existing semantics.
code
swift · 23 lines// Swift 6 language mode, no upcoming features enabled.
final class RequestLog { // not Sendable
private var lines: [String] = []
func flush() async { lines.removeAll() } // leaves the caller's actor
nonisolated(nonsending)
func flushOnCaller() async { lines.removeAll() } // stays on the caller's actor
@concurrent
func lineCount() async -> Int { lines.count } // always leaves the caller's actor
}
@MainActor
final class SyncCoordinator {
let log = RequestLog()
func finishSync() async {
await log.flushOnCaller() // OK: log never leaves the main actor
// await log.flush() -> error: sending 'self.log' risks causing data races
// await log.lineCount() -> the same error
}
}go deeper
Recall that an async method on a plain class may run away from the main actor, and that Swift 6 checks what you pass to it.
Explain the default execution rule for nonisolated async functions and why the receiver counts as a value being sent.
Choose nonisolated(nonsending) or @concurrent per function, and explain why the upcoming feature is opt-in, with a migrate mode, rather than part of Swift 6 mode.
Decide whether a codebase adopts NonisolatedNonsendingByDefault now, weighing fewer sending errors against work silently moving onto callers' actors.
## The rule that causes the error Synchronous nonisolated functions always run wherever their caller runs. **Asynchronous** nonisolated functions, under the default rules, do not: they switch to the **global concurrent executor**, off the caller's actor, for their whole body. That applies to any `async` method of a type with no isolation, such as an ordinary class. So when main-actor code awaits an async method on a non-`Sendable` object it owns, the object would be used by the method on the concurrent executor while the main actor, suspended at the `await`, is free to run other code that touches the same object. Region-based isolation sees the receiver (`self` of the callee) being sent from the main actor's region and rejects it in Swift 6 language mode: ``` error: sending 'self.log' risks causing data races note: sending main actor-isolated 'self.log' to @concurrent instance method 'flush()' risks causing data races between @concurrent and main actor-isolated uses ``` The note already uses the new vocabulary: the default for this method is `@concurrent`. ## Why the old default existed Switching nonisolated async functions off the caller's actor was meant to keep actors free: a slow helper would not hold up other work queued on that actor. In practice the compiler's own documentation for the upcoming feature lists the costs: - `nonisolated` is hard to understand, because synchronous and asynchronous nonisolated functions run in different places; - an async function that simply runs where its caller runs was difficult to express; - it was easy to write async APIs on non-`Sendable` types that could never be called from an actor; - higher-order async APIs that take and call closures were awkward to write correctly. ## `nonisolated(nonsending)` (SE-0461, Swift 6.2) Writing `nonisolated(nonsending)` on an async function makes it **run on the caller's actor**. The compiler passes the caller's isolation along implicitly, so: - called from the main actor, it runs on the main actor; called from an actor, on that actor; called from nonisolated code, it stays nonisolated; - its arguments and its receiver are **not sent** anywhere, so non-`Sendable` values are fine; - it behaves like a synchronous nonisolated function that happens to be able to suspend. Under the hood the compiler implicitly passes the caller's actor as an optional parameter, and the function's body runs on that actor's executor; inside, `#isolation` can forward it to APIs that take an `isolated (any Actor)?` parameter. This is the fix the compiler's own documentation for the "sending risks causing data races" diagnostic calls the most common one. ## The two spellings and the upcoming feature | Spelling | Where the async function runs | Arguments cross a boundary? | |---|---|---| | unannotated `nonisolated` async (default today) | global concurrent executor | yes | | `@concurrent` | global concurrent executor, always | yes, so non-`Sendable` ones must be disconnected values the caller gives up | | `nonisolated(nonsending)` | the caller's actor | no | | unannotated, with `NonisolatedNonsendingByDefault` enabled | the caller's actor | no | `NonisolatedNonsendingByDefault` is an **upcoming feature** belonging to a future language mode: Swift 6 language mode does **not** turn it on. Enable it with `-enable-upcoming-feature NonisolatedNonsendingByDefault`. Because it changes where existing code runs, it has a migration mode, `-enable-upcoming-feature NonisolatedNonsendingByDefault:migrate`, whose fix-its add `@concurrent` to existing nonisolated async functions and closures so their behaviour stays the same while new code gets the new default. ## Choosing between them 1. Use **`nonisolated(nonsending)`** for async helpers that work on the caller's data: logging, small transformations, wrappers that await something else. They get simpler data-race rules and fewer executor hops. 2. Use **`@concurrent`** for work that must leave the caller's actor, such as CPU-heavy parsing or compression, so it does not block the main actor. Accept that its inputs cross a boundary: they must be `Sendable`, or fresh non-`Sendable` values the caller never touches again. 3. Do not assume `nonisolated(nonsending)` moves work off the main thread: called from the main actor, a long synchronous loop inside it blocks the main actor, exactly as if the code were written inline. ## What the fix does not change - It does not make `RequestLog` `Sendable`; you still cannot capture it in a `Task.detached` or send it to another actor. - Isolated methods of actors and `@MainActor` types are unaffected; this is only about nonisolated async functions. - `@concurrent` cannot be combined with `@MainActor` or with an isolated parameter, because it means "nonisolated, and always switch". - Both spellings work in Swift 5 and Swift 6 language modes from Swift 6.2 on.
- After adding nonisolated(nonsending) to a parser method called from the main actor, the UI stutters. Why?`nonisolated(nonsending)` runs the method on the caller's actor, so a long synchronous loop inside it now runs on the main actor and blocks it until the next suspension point. CPU-heavy work belongs in a `@concurrent` function, whose inputs then cross a boundary and must be `Sendable` or values the caller gives up.
- What happens to existing async code when a module enables NonisolatedNonsendingByDefault?Every unannotated nonisolated async function starts running on its caller's actor instead of the global concurrent executor. That removes some sending errors but can move work onto the main actor. The `:migrate` mode adds `@concurrent` to existing functions and closures so their behaviour is preserved, and you remove it where caller-actor execution is what you want.
- Swift 6 language mode already runs nonisolated async functions on the caller's actor.
- nonisolated(nonsending) moves the function off the main thread.
- The fix is to make the non-Sendable class an actor in every case.
- @concurrent is a new name for nonisolated(nonsending).
- Synchronous nonisolated functions also hop to the global executor.
Assumes Swift 6.4; nonisolated(nonsending) and @concurrent arrived in Swift 6.2 (SE-0461), and NonisolatedNonsendingByDefault is an upcoming feature that Swift 6 language mode does not enable.