skip to content

In Swift 6 language mode, why may a Task capture a freshly created non-Sendable ResponseCache but not one stored on self, and what does sending add?

level: seniorimportance: must knowfreq 55%

answer

  1. values grouped by who can reach them
  2. fresh value: disconnected
  3. Task.init takes a sending closure
  4. no use after the send
  5. self is the caller's

basics

~20 s

Region-based isolation lets a non-Sendable value move into a Task when nothing else can reach it afterwards: a fresh local cache can, one reached through self cannot, because the caller still holds self. A sending parameter writes that hand-over into a signature.

solid answer

~50 s

Since Swift 6.0, the compiler groups non-Sendable values into isolation regions. A newly created value sits in its own disconnected region, and `Task.init` takes its closure as `sending`, not `@Sendable`, so a closure that captures only that fresh `ResponseCache` may move into the task, provided the creator never touches the cache again. A cache stored on `self` lives in the region of the `self` parameter, which the caller can still reach, so Swift 6 mode reports "passing closure as a 'sending' parameter risks causing data races …". The fixes are to make the cache `Sendable` and capture it with `[cache]`, isolate the owner to an actor such as `@MainActor`, or hand a disconnected value through a `sending` parameter, which the caller may not use after the call. Swift 5 mode shows these as warnings only under `-strict-concurrency=complete`.

code

swift · 22 lines
swift
// Swift 6 language mode. ResponseCache is not Sendable.
final class ResponseCache {
    private var entries: [String: [UInt8]] = [:]
    func store(_ bytes: [UInt8], for key: String) { entries[key] = bytes }
}

final class FeedLoader {
    let cache = ResponseCache()

    func prefetch(_ key: String) {
        Task {                                  // error: see caption
            cache.store([1, 2, 3], for: key)
        }
    }
}

func warmUp() {
    let cache = ResponseCache()                 // a disconnected region
    Task {                                      // OK: the region moves into the task
        cache.store([0], for: "/warm")
    }
}

go deeper

for a junior

Remember that Swift 6 lets a brand-new object move into a Task as long as you stop using it after the Task starts.

for a middle

Explain disconnected regions, why a fresh value can be sent, and why a stored property reached through self cannot.

for a senior

Diagnose the 'passing closure as a sending parameter' error from its self note, and choose between a capture list, actor isolation and a sending parameter.

for a principal

Weigh designing APIs with sending parameters and results, which keep types non-Sendable and flexible, against making shared types Sendable for every caller.

## The problem region-based isolation solves Before Swift 6.0, a value could cross an isolation boundary only if its type was `Sendable`. That rejected plenty of safe code: a non-`Sendable` object created in one function, handed to a task and never touched again by its creator cannot race with anything. **Region-based isolation** (SE-0414, Swift 6.0) lets the compiler prove exactly that, so many non-`Sendable` types no longer need to become `Sendable` just to be handed over. ## Regions in four rules - Every non-`Sendable` value belongs to an **isolation region**: a group of values that may reference each other and must therefore travel together. - A freshly created value, such as `let cache = ResponseCache()`, starts in its own **disconnected** region. - Storing one value inside another (`loader.cache = cache`) **merges** their regions; sending either one now sends both. - A value that other code can reach (a parameter, `self` included, an actor's stored property, a global) belongs to the **task-isolated** or **actor-isolated** region of the current context. It cannot be sent away, because whoever passed it in may still use it. Sending a disconnected region across a boundary is legal as long as the sender does not use anything in that region afterwards. A later use turns the send into an error, with a note pointing at the access that "can happen concurrently". ## Why the two Task captures differ `Task.init` declares its body as `sending @escaping @isolated(any) () async throws -> Success`: the closure is **sending**, not `@Sendable`. A closure that captures non-`Sendable` values is itself non-`Sendable`, so the question becomes whether the closure's captures form a region the caller can give up. | Capture | Region | Swift 6 mode result | |---|---|---| | `let cache = ResponseCache()` then `Task { cache.store(...) }`, cache unused afterwards | disconnected | compiles | | the same, but the function calls `cache.store(...)` after the `Task` | disconnected, used after the send | error: sending value of non-Sendable type '() async -> ()' risks causing data races | | `Task { cache.store(...) }` inside a method of a non-`Sendable` `FeedLoader`, where `cache` is a stored property | the `self` parameter's region | error: passing closure as a 'sending' parameter risks causing data races between code in the current isolation context and concurrent execution of the closure | In the third row the note reads "closure captures 'self' which is accessible to code in the current isolation context". The closure never names `self`, but reading `cache` means capturing `self`. ## Fixing the `FeedLoader` capture 1. **Make the cache `Sendable` and capture only the cache**: `Task { [cache] in cache.store(...) }`. Making `ResponseCache` `Sendable` alone is not enough, because the closure still captures the non-`Sendable` `self`. 2. **Give the owner an isolation**: in a `@MainActor final class FeedLoader` (or an actor), the `Task` inherits that isolation, so nothing crosses a boundary and the capture compiles. 3. **Hand over a disconnected value** with `sending`, as below, when the work really belongs to whoever created the cache. 4. **Last resort**: `nonisolated(unsafe)` on a local copy or `@unchecked Sendable` on the type, which switch the check off rather than satisfy it. ## `sending` parameters and results (SE-0430, Swift 6.0) Normally a non-`Sendable` parameter is in the caller's region, so the callee cannot send it anywhere. Marking it **`sending`** changes the contract on both sides: - the **caller** must pass a value in a disconnected region and may not use it after the call ("'cache' used after being passed as a 'sending' parameter; Later uses could race"); - the **callee** may send it on, into a `Task` or to an actor. A **`sending` result** (`func makeCache() -> sending ResponseCache`) promises the caller a disconnected value it can send or merge into actor state. The standard library uses both: `Task.init` takes a `sending` closure, and the Synchronization module's `Mutex` is created with `init(_ initialValue: consuming sending Value)`. ## Where the diagnostics appear These are flow-sensitive checks that run after type checking, so a type-check-only pass (`swiftc -typecheck`) does not report them; a real build does. In Swift 5 language mode with default checking you see nothing, and with `-strict-concurrency=complete` you see the same messages as warnings suffixed "this is an error in the Swift 6 language mode".

  • You make ResponseCache Sendable, but the Task inside FeedLoader still fails. Why?
    The closure reads `cache` through `self`, so it captures the non-`Sendable` `FeedLoader`, and `self` is still reachable by the caller. Capture the cache alone with `Task { [cache] in ... }`, which copies the now-`Sendable` reference, or isolate `FeedLoader` to `@MainActor` or an actor so the task inherits its isolation and nothing crosses a boundary.
  • After `loader.cache = cache`, you send `loader` into a Task and then touch `cache`. What does Swift 6 mode say?
    It is an error. Storing `cache` inside `loader` merged their regions, so sending `loader` sent `cache` as well, and the later access is flagged as one that can happen concurrently with the task. Finish all work on `cache` before the send, or do it inside the task.
  • Why do region errors not show up when you run `swiftc -typecheck`?
    Region-based isolation is a flow-sensitive analysis that runs after type checking, on the compiled function body, so a type-check-only pass stops before it. A normal build reports them. In Swift 5 language mode they also need `-strict-concurrency=complete` before they appear as warnings.

Handing a sealed parcel to a courier: once you have given it away you may not open it again, but a parcel still sitting on a shared office desk cannot be handed over, because a colleague may pick it up.

  • Task's closure is @Sendable, so it can never capture a non-Sendable value.
  • Making the cache Sendable fixes any Task that touches it through self.
  • A sending parameter copies the value, so the caller can keep using it.
  • Region checks run at run time, so the build cannot catch them.
  • Swift 5 mode reports region errors by default.

Assumes Swift 6.4; region-based isolation (SE-0414) and sending (SE-0430) shipped in Swift 6.0, are errors in Swift 6 language mode and warnings in Swift 5 mode only under -strict-concurrency=complete.