HeadlinesBriefing favicon HeadlinesBriefing.com

Swift Concurrency: Understanding Detached Tasks

DEV Community •
×

A detached task in Swift concurrency runs an operation asynchronously, completely outside the parent's structured concurrency context. This means it doesn't inherit the priority or cancellation state of its parent. Developers create one using `Task.detached()`, which is useful for operations that must run independently, like a background cleanup process that shouldn't be tied to a parent task's lifecycle.

The key risk involves cancellation. Since detached tasks don't inherit the cancellation state, calling `Task.checkCancellation()` inside them has no effect. If a parent task is cancelled, any detached tasks it launched will continue running. To cancel a detached task, you must maintain a reference to it and call `cancel()` manually.

This pattern is appropriate for truly independent operations that can complete regardless of their parent's fate. For example, a detached task could handle a directory cleanup that should finish even if the initiating function returns. However, it requires careful design, as these tasks aren't automatically cleaned up and must be managed explicitly to prevent resource leaks.