In Swift, how does a `@TaskLocal` value carry a request ID into every log line of an upload, and which tasks can read it?
answer
- context that rides with the task
- static or global declaration
- bound for a scope, never assigned
- children and Task { } see it
- detached tasks read the default
basics
~20 sDeclare @TaskLocal static var requestID: String?, bind it with $requestID.withValue(id) { ... }, and code in that scope reads it like a static property. Child tasks and Task { } inherit the binding; Task.detached reads the default.
solid answer
~50 sA `@TaskLocal` is a static property or, since Swift 6.0, a global variable whose value is bound per task rather than stored once. You cannot assign it; `$requestID.withValue("req-7f3a") { ... }` binds the value for exactly the duration of that closure, and any function called inside it, synchronous or async, reads `UploadLog.requestID` without the ID being threaded through parameters. Child tasks created in the scope, in task groups or with `async let`, see the binding, and `Task { }` copies it into the new task. `Task.detached` does not inherit it, so code there reads the declared default. When the scope ends, the previous value is visible again. The value type must be `Sendable`, which Swift 6 language mode enforces as an error. Bind around the whole group or inside a child, not around a single `addTask` call in the group body.
code
swift · 28 linesenum UploadLog {
@TaskLocal static var requestID = "none"
}
func log(_ message: String) {
print("[\(UploadLog.requestID)] \(message)")
}
func uploadBatch(_ names: [String]) async {
await UploadLog.$requestID.withValue("req-7f3a") {
log("batch started")
await withTaskGroup(of: Void.self) { group in
for name in names {
group.addTask { log("sending \(name)") } // child task: inherits
}
}
Task.detached { log("detached audit") } // detached: default value
}
log("batch finished") // scope ended
}
@main
struct Demo {
static func main() async {
await uploadBatch(["IMG_1.jpg", "IMG_2.jpg"])
try? await Task.sleep(for: .milliseconds(50))
}
}go deeper
Recall that @TaskLocal holds per-task context such as a request ID, and that you bind it with withValue rather than assigning it.
Explain which tasks inherit a binding, why detached tasks read the default, and why the value type must be Sendable.
Show where to bind around a task group, how nested bindings shadow, and when a parameter is safer than a task-local.
Decide which cross-cutting context, such as trace IDs or tenant IDs, a codebase standardises as task-locals and which stays explicit.
## The problem task-locals solve In the photo uploader every log line should carry the request ID of the upload batch that produced it. Passing `requestID` as a parameter through every function, including ones that have nothing to do with logging, is noisy and easy to forget. A global variable is wrong too: two batches running at once would overwrite each other's ID. A **task-local value** is a third option: context attached to the **current task** and visible to everything that task runs, including the child tasks it spawns. ## Declaring, binding and reading - **Declaring:** put `@TaskLocal` on a `static` property or, since Swift 6.0, a global variable. Since Swift 6.0, `@TaskLocal` is a macro that expands to a `TaskLocal<Value>` stored in a `$`-prefixed projection, `$requestID`. Applying it to an instance property is an error: "'@TaskLocal' can only be applied to 'static' property, or global variables". - **Default:** the initial value is what readers get when nothing is bound. An optional with no initializer defaults to `nil`. - **Binding:** the property is get-only ("cannot assign to property: 'requestID' is a get-only property"). You bind it with `UploadLog.$requestID.withValue("req-7f3a") { ... }`. The value holds for exactly that closure and is restored afterwards, so bindings nest like scopes: an inner `withValue` shadows the outer one until it returns. - **Reading:** `UploadLog.requestID` reads like any static property, from async or synchronous code. Outside any task, `withValue` falls back to a thread-local, so a synchronous caller still sees the value inside the scope. ## Which tasks see the binding | Created inside the `withValue` scope | Reads the bound value? | |---|---| | Code called directly in the closure | Yes | | A child added with `group.addTask` | Yes | | An `async let` child | Yes | | An unstructured `Task { }` | Yes, the bindings are copied at creation | | `Task.detached { }` | No, it reads the declared default | | Code that runs after `withValue` returns | No, the previous value is back | The copy into `Task { }` is a snapshot: the new task keeps the value it was created with even after the creator's scope ends. Inheritance is how the logger works with no plumbing. The batch binds the ID once around a task group, every upload child logs with it, and an unrelated detached maintenance job keeps logging with the default. ## Rules the compiler and runtime enforce 1. **Sendable values.** `TaskLocal` is declared `TaskLocal<Value: Sendable>`, because the value is shared with child tasks running concurrently. In Swift 6 language mode a non-`Sendable` value type is a compile error; Swift 5 mode with minimal checking does not report it. 2. **No assignment.** Every change is a scoped `withValue` binding, which is what makes the value predictable for every task that reads it. 3. **Where to bind around a group.** The runtime's own diagnostic text spells out the safe placements: bind around the whole `withTaskGroup` call, or inside a specific child's closure. Binding inside the group body around one `addTask` call was reported as illegal by older runtimes; since Swift 6 the runtime copies the value defensively instead of trapping, but the two documented placements are the ones that read clearly. ## When task-locals are the wrong tool - **Results or mutable state.** A task-local carries context **down** the task tree; nothing flows back up. Return values or an actor carry results. - **Required inputs.** If a function cannot work without a value, make it a parameter; a missing task-local silently becomes the default. - **Tests that forget to bind.** A test that never calls `withValue` exercises the default path only; bind the value in the test the same way the production entry point does. - **Too many of them.** Task-locals suit cross-cutting context such as trace IDs, request IDs and test-scoped configuration, not a general-purpose dependency container. The idea of thread-local storage in general, and why pooled threads make it leak between jobs, is covered with process memory layout; what Swift adds is that the binding follows the **task**, across suspension points and thread hops, and is inherited by child tasks.
- A `Task { }` created inside `withValue` runs after the scope has ended. Which value does it read?The bound one. `Task { }` copies the creating task's task-local bindings when it is created, so the new task keeps reading "req-7f3a" for its whole life, even though code in the creator now reads the default again after `withValue` returned.
- How would you give one particular upload in a group a different request ID?Bind inside that child's closure: `group.addTask { await UploadLog.$requestID.withValue("req-retry") { ... } }`. The inner binding shadows the outer one for that child only, and its siblings keep reading the batch ID.
- You set a task-local by assigning to the static property.
- Task.detached inherits task-local values just like Task { } does.
- A task-local binding stays in place after withValue returns.
- Changes made in a child task's binding flow back to the parent.
- Any type can be stored in a task-local, Sendable or not.
Assumes Swift 6.4; since Swift 6.0 @TaskLocal is a macro and may be applied to global variables, and Swift 6 language mode reports a non-Sendable task-local value as an error.