Browse Questions
- Instruments diagnoses memory issues through the Leaks instrument for automated heap scans and the Allocations instrument with Mark Generation for tracking persistent abandoned memory.
- Tasks support cooperative cancellation — you cancel from outside, and the task must check for cancellation and stop itself.
- A Task is Swift's unit of async work.
- Delegation is a pattern where one object hands off responsibility to another through a protocol, letting a child communicate back to its owner without knowing its concrete type.
Answer:
A Task is Swift's unit of async work. Unlike threads, tasks are lightweight, managed by the Swift runtime, and can be suspended without blocking an underlying thread.
Task | Thread | |
|---|---|---|
| Cost | Lightweight | Heavy (~512KB stack) |
| Managed by | Swift runtime | OS |
| Suspension | Yes (non-blocking) | No (blocks thread) |
| Cancellation | Built-in | Manual |
Code Example:
// Creating a task
let task = Task {
let data = try await fetchData()
await MainActor.run { updateUI(with: data) }
}
// Cancelling it
task.cancel()
// Task inherits priority and actor context from where it's created
// Use Task.detached to explicitly break that inheritance
Task.detached(priority: .background) {
await expensiveBackgroundWork()
}