ConcurrencyMidMCQ

What is a `Task` and how is it different from a `Thread`?

Test your knowledge:

Explanation & Code

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.

TaskThread
CostLightweightHeavy (~512KB stack)
Managed bySwift runtimeOS
SuspensionYes (non-blocking)No (blocks thread)
CancellationBuilt-inManual

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()
}

Rate your understanding:

Ready to practice more Concurrency?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.