In Swift, what does a `Task { }` created inside a `@MainActor` method inherit, and why is `Task.detached` rarely the right tool?
answer
- three things travel with Task { }
- isolation, priority, task-locals
- cancellation does not travel
- detached starts from nothing
- Task.immediate starts on the caller
basics
~20 sTask { } inherits the creator's actor isolation, base priority and task-local values, but not its cancellation. Task.detached inherits none of these, so it is rarely right: you lose context and must hop back to the main actor yourself.
solid answer
~50 sCreated in a `@MainActor` method, `Task { }` runs its body on the main actor, so it can touch main-actor state without `await`; it also takes the current task's base priority and copies its `@TaskLocal` values. It is still unstructured, so cancelling the creating task does not cancel it. `Task.detached` drops all three: the body runs with no actor isolation, its priority defaults to `.medium` unless you pass one, and task-local values read their defaults. That is rarely what you want. To move CPU work off the main actor, call a nonisolated `async` function, or a child task in a group, and keep priority and context flowing. Reach for `Task.detached` only when the work must deliberately not inherit the caller's priority or task-locals. Swift 6.2 adds `Task.immediate`, which starts the body synchronously on the caller until its first suspension.
code
swift · 30 linesenum UploadLog {
@TaskLocal static var requestID: String?
}
@MainActor
final class UploadViewModel {
var status = "idle"
func startTapped() async {
await UploadLog.$requestID.withValue("req-42") {
let inherited = Task {
self.status = "uploading" // main actor: no await needed
return (Task.basePriority, UploadLog.requestID)
}
let detached = Task.detached {
// self.status = "x" would need: await MainActor.run { ... }
return (Task.basePriority, UploadLog.requestID)
}
print("Task: ", await inherited.value)
print("detached:", await detached.value)
}
}
}
@main
struct Demo {
static func main() async {
await Task(priority: .high) { await UploadViewModel().startTapped() }.value
}
}go deeper
Remember that Task { } in main-actor code runs on the main actor, and that Task.detached does not.
List the three things Task { } inherits, isolation, base priority and task-locals, and the one it does not, cancellation; then contrast each with Task.detached.
Explain how you move CPU work off the main actor without detaching, how priority escalation works on await, and when Task.immediate changes ordering.
Decide whether a codebase should ban Task.detached outside a reviewed allow-list, given what it silently drops in priority and logging context.
## Two ways to create an unstructured task Both `Task { }` (the initializer `Task.init(name:priority:operation:)`) and `Task.detached(name:priority:operation:)` create an **unstructured task**: a task with no parent, which nothing awaits automatically and which you cancel through its handle. They differ in how much of the **current context** the new task carries. The Swift book puts it in one sentence each: `Task { }` "defaults to running with the same actor isolation, priority, and task-local state as the current task"; a detached task "defaults to running without any actor isolation and doesn't inherit the current task's priority or task-local state." | Property | `Task { }` | `Task.detached` | |---|---|---| | Actor isolation | The creating context's, e.g. the main actor | None by default: runs on the global concurrent executor | | Base priority | The creating task's base priority | `.medium` unless you pass `priority:` | | `@TaskLocal` values | Copied from the creating task | Not inherited; reads see defaults | | Cancellation of the creator | Not inherited | Not inherited | ## What inheriting isolation means in practice In a `@MainActor` view model, a closure passed to `Task { }` is itself main-actor isolated. It can assign `self.status = "uploading"` with no `await`, and every synchronous line in it runs on the main actor. That cuts both ways: - **Good:** UI-facing state updates need no hop and no `MainActor.run`. - **Risky:** heavy synchronous work placed directly in the closure, such as resizing 50 images in a loop, blocks the main actor just as it would in the action itself. Only the `await`ed calls can run elsewhere. The same closure written as `Task.detached { self.status = "uploading" }` does not compile, in Swift 5 or Swift 6 language mode: "main actor-isolated property 'status' can not be mutated from a nonisolated context". The detached body is nonisolated, so it must `await MainActor.run { ... }` or call a main-actor method with `await`. The finer rules for isolation inside an actor's own methods belong to the material on actors. ## Priority and task-locals An unstructured `Task { }` with no `priority:` argument takes the creating task's base priority (when the creator is a thread running at user-interactive quality of service, such as the main thread outside any task, the runtime downgrades that to `.userInitiated`). A detached task with no argument gets the default, `.medium`, whatever the caller's priority. Priority can still rise later: when a higher-priority task awaits a lower-priority one, the runtime **escalates** the awaited task, so `Task.currentPriority` inside it can read higher than `Task.basePriority`. Swift 6.2 (SE-0462) adds `escalatePriority(to:)` on a handle and `withTaskPriorityEscalationHandler(operation:onPriorityEscalated:)` to react to it. `@TaskLocal` values bound with `withValue` are copied into a `Task { }`, so a request ID used for logging survives the hop. A detached task reads each task-local's declared default instead. ## Why `Task.detached` is rarely right The standard library's own documentation advises against it: don't use a detached task if the operation can be modelled with structured concurrency, because child tasks inherit priority and task-local storage and are cancelled with their parent. Common reasons people reach for it, and what to do instead: 1. **"Get the work off the main thread."** Call a nonisolated `async` function instead. By default it runs on the global concurrent executor; in a module that enables the upcoming feature `NonisolatedNonsendingByDefault`, mark it `@concurrent` (Swift 6.2) to keep that behaviour. 2. **"Run things in parallel."** Use a task group or `async let` inside the current task, so cancellation and priority flow to the children. 3. **"It must outlive the screen."** A plain `Task { }` already outlives its creator; detaching adds nothing to lifetime. Legitimate uses are narrow: background maintenance that should deliberately not inherit a user-initiated priority or a request's task-locals, started with an explicit low priority. ## `Task.immediate` Swift 6.2 (SE-0472) adds `Task.immediate { }` (and `Task.immediateDetached`, and `addImmediateTask` on groups). Instead of being enqueued, the new task **starts running synchronously on the calling thread** until its first real suspension, then resumes on the executor its isolation requires. Called from a main-actor action, code before the first `await` runs before the action's next line, which is useful when state must be set in the same turn. Apart from where it starts, an immediate task behaves like `Task { }`.
- If a `Task { }` in a `@MainActor` method awaits a slow network call, is the main actor blocked during the call?No. At the `await` the task suspends and the main actor is free to run other work; the call itself runs wherever its own isolation says. Only the synchronous code between suspension points occupies the main actor, which is why CPU-heavy loops inside such a task still freeze the UI.
- Why can `Task.currentPriority` inside a detached task read `.high` when its base priority is `.medium`?Because a higher-priority task awaited it. Awaiting a task's value escalates the awaited task to the waiter's priority so the waiter is not held up by low-priority work; `Task.basePriority` keeps the priority the task was created with, while `currentPriority` shows the escalated one.
- When does `Task.immediate` change observable behaviour compared with `Task { }`?When code before the first suspension point matters to the caller's ordering. With `Task.immediate`, that prefix runs synchronously before the creating function's next line; with `Task { }` it runs later, when the executor gets to the enqueued job. After the first real suspension, both behave the same.
- Task.detached is how you get work off the main thread.
- Cancelling the creating task also cancels a Task { } it created.
- Task { } always runs its body on a background thread.
- A detached task inherits the caller's priority unless you pass one.
- Task.detached makes the task live longer than Task { } does.
Assumes Swift 6.4; Task.immediate (SE-0472), priority escalation APIs (SE-0462) and @concurrent (SE-0461) arrived in Swift 6.2.