Swift Concurrency Programming: async and await
Downloading images, reading files, and requesting APIs all wait on external devices or the network, taking far longer than CPU computation.
If the main thread is made to wait, the UI will freeze.
Swift uses async / await (SE-0296, introduced in Swift 5.5) to turn "waiting" into a language-level feature, making asynchronous code read as linearly as synchronous code.
What problem does concurrency solve
The traditional approach to concurrency is nested callbacks: start request B inside the callback of request A, then handle the result in B's callback.
Such code is deeply nested, scatters error handling, and easily misses a branch.
Swift's concurrency model does three things: mark asynchronous functions with async, wait at the call site with await, and manage task lifecycles with Task.
| Concept | Syntax | Purpose |
|---|---|---|
| Asynchronous functions | func f() async -> T |
Declares that this function may suspend and wait |
| Waiting | let x = await f() |
Suspends the current task and resumes when the result is ready |
| Task | Task { ... } |
Creates an independent unit of concurrent execution |
| Task group | withTaskGroup |
Dynamically executes a batch of tasks of the same type concurrently |
| Executor isolation | @MainActor |
Ensures code runs on a specified thread, such as the main thread |
await It's not "blocking" but "suspending." The current task yields execution, freeing the thread to do other work, and resumes when the result arrives. This is the fundamental difference between it and sleep blocking a thread.
async functions and await
Marking a function as async means its execution may pause along the way.
Call sites must write await, which syntactically marks "waiting happens here."
Define an asynchronous function
The example below simulates two network requests, using Task.sleep to represent waiting time.
Example
import Foundation
// async marks an asynchronous function; the body may suspend and wait
func fetchPage
(
_ name
:
String
)
async
String
{
try
?
await Task.
sleep
(
for
:
.
milliseconds
(
20
)
)
return
"(name) content"
}
func loadAll
(
)
async
{
// await indicates a suspension here; continue when the result arrives
let home
=
await fetchPage
(
"RUNOOB homepage"
)
let doc
=
await fetchPage
(
"Swift Tutorial"
)
(
home
)
(
doc
)
}
await loadAll
(
)
Running result:
RUNOOB 首页 内容
Swift 教程 内容
The two requests are serial: the second starts only after the first returns.
If there's no dependency between them, they can run concurrently, as covered later with async let.
In scripts, Playgrounds, and main.swift in top-level code you can write directly await. In a regular function, use await, and the function itself must be marked as async。
await is a suspension point
When execution reaches await, the current task suspends and yields the thread to other tasks.
Once the result is ready, the task continues from that line.
Because other tasks may interleave, don't assume "the state hasn't changed" across an await; this is explored further in the article on actors.
async throws: both waiting and failing
An asynchronous function can also throw errors, written by placing both keywords side by side after the parameter list.
Example
import Foundation
enum
FetchError
:
Error
{
case
badStatus
(
Int
)
}
// async throws: can both suspend and throw errors
func fetchScore
(
_ id
:
Int
)
async throws
Int
{
try
await Task.
sleep
(
for
:
.
milliseconds
(
10
)
)
guard id
0
else
{
throw
FetchError.
badStatus
(
id
)
}
return
id
10
}
do
{
let score
=
try
await fetchScore
(
7
)
(
"Score: (score)"
)
let bad
=
try
await fetchScore
(
1
)
(
bad
)
}
catch
{
(
"Error: (error)"
)
}
Running result:
分数:70
出错:badStatus(-1)
Note the order of the keywords is try await.
Inside do-catch, errors thrown by try await are handled by catch just as with synchronous functions.
Task and structured concurrency
Having only async functions isn't enough; someone must "initiate" the first asynchronous call.
Swift offers two approaches: Task creates an independent task, while async let and TaskGroup organize structured concurrency.
Task: independent tasks
Task { } creates a new concurrent task that starts executing immediately.
Its return value is retrieved via task.value, which requires await.
Example
import Foundation
func fetchPage
(
_ name
:
String
)
async
String
{
try
?
await Task.
sleep
(
for
:
.
milliseconds
(
20
)
)
return
"(name) content"
}
// Task creates an independent concurrent task and starts it immediately
let t1
=
Task
{
await fetchPage
(
"Task A"
)
}
let t2
=
Task
{
await fetchPage
(
"Task B"
)
}
// Wait for results in a fixed order, so the output order is deterministic
(
await t1.
value
)
(
await t2.
value
)
Running result:
任务甲 内容
任务乙 内容
The two tasks do run concurrently, but here values are read in the order t1, t2, so the output order is stable.
Task A created task isn't bound by the current scope; even if the outer function has returned, the task may keep running. Such tasks are called "unstructured tasks." Prefer structured concurrency whenever possible.
async let: concurrently executing a fixed number of tasks
When the number of asynchronous calls is fixed and they're independent of each other, async let (SE-0317, introduced in Swift 5.5) is the most concise choice.
It lets expressions start evaluating in the background immediately, waiting only when you actually need the result.
Example
import Foundation
func fetchPage
(
_ name
:
String
)
async
String
{
try
?
await Task.
sleep
(
for
:
.
milliseconds
(
20
)
)
return
"(name) content"
}
func loadPair
(
)
async
{
// async let starts both requests at once without blocking the current task
async let first
=
fetchPage
(
"async let A"
)
async let second
=
fetchPage
(
"async let B"
)
// Wait for both results together here
let results
=
await
(
first, second
)
(
results.0
)
(
results.1
)
}
await loadPair
(
)
Running result:
async let 甲 内容
async let 乙 内容
Both requests are launched simultaneously, so the total time is close to one request rather than two.
TaskGroup: concurrency count decided at runtime
If the number of tasks depends on runtime data—for example, concurrently downloading all the URLs in an array—use a task group.
Structured concurrency (SE-0304, introduced in Swift 5.5) guarantees that all child tasks are awaited before leaving the scope, so nothing leaks.
Example
import Foundation
// A task group is for concurrency where "the count is known only at runtime"
func loadNumbers
(
)
async
[
Int
]
{
await withTaskGroup
(
of
:
Int.
self
)
{
group in
for
i in
1
...
4
{
group.
addTask
{
i
100
}
}
var results
:
[
Int
]
=
[
]
for
await value in group
{
results.
append
(
value
)
}
// Completion order isn't guaranteed; sort before outputting for stable results
return
results.
sorted
(
)
}
}
(
await loadNumbers
(
)
)
Running result:
[100, 200, 300, 400]
A task group returns results in "completion order," not "addition order." When a fixed order is needed, either sort as in the example or attach an index to each task and rearrange.
Cancellation and Timeouts
Once an asynchronous task is launched, you need a way to tell it "no need to continue"—for example, the user left the page or the request timed out.
Cancellation in Swift is "cooperative": calling cancel() merely marks the task as canceled; how to respond is up to the task itself.
Inside a task, you can check the status with Task.isCancelled or use Task.checkCancellation() to throw immediately if canceled.
Example
import Foundation
func step
(
_ n
:
Int
)
async throws
Int
{
// Actively check cancellation status; throw CancellationError if canceled
try
Task.
checkCancellation
(
)
try
await Task.
sleep
(
for
:
.
seconds
(
1
)
)
return
n
n
}
let job
=
Task
{
try
await step
(
4
)
}
job.
cancel
(
)
// Request cancellation immediately
do
{
(
try
await job.
value
)
}
catch
is CancellationError
{
(
"Task was canceled"
)
}
Running result:
任务被取消
Many standard library APIs include cancellation checks; for example, Task.sleep throws CancellationError when canceled, so you don't need to check manually.
If your own loop contains no await, you must check manually, or the cancellation signal will never be handled.
Example
// Actively check for cancellation inside the loop and exit promptly
func countUp
(
)
async
Int
{
var total
=
0
for
i in
1
...
1
_000_000
{
if
Task.
isCancelled
{
break
}
// Stop as soon as a cancellation signal arrives
total
=
i
}
return
total
}
There's no built-in syntax for timeouts; a common approach is to race the business task against a timer task and use whichever finishes first.
Example
import Foundation
enum
FetchError
:
Error
{
case
timedOut
}
// Timeout control: race the business task against a timer task and use whichever finishes first
func withTimeout
<
T
:
Sendable
(
seconds
:
Double,
operation
:
@escaping @Sendable
(
)
async throws
T
)
async throws
T
{
try
await withThrowingTaskGroup
(
of
:
T.
self
)
{
group in
group.
addTask
{
try
await operation
(
)
}
group.
addTask
{
try
await Task.
sleep
(
for
:
.
seconds
(
seconds
)
)
throw
FetchError.
timedOut
}
let result
=
try
await group.
next
(
)
!
group.
cancelAll
(
)
// Cancel the task that hasn't finished
return
result
}
}
do
{
let fast
=
try
await withTimeout
(
seconds
:
1
)
{
try
await Task.
sleep
(
for
:
.
milliseconds
(
10
)
)
return
"RUNOOB returns quickly"
}
(
fast
)
let slow
=
try
await withTimeout
(
seconds
:
0.1
)
{
try
await Task.
sleep
(
for
:
.
seconds
(
2
)
)
return
"never returns"
}
(
slow
)
}
catch
{
(
"Timeout: (error)"
)
}
Running result:
RUNOOB 快速返回
超时:timedOut
| API | Purpose | Typical scenario |
|---|---|---|
| task.cancel() | Requests cancellation of a task without forcing an interrupt | User leaves the page or the page closes |
| Task.isCancelled | Checks whether the current task has been canceled | Manual checks inside long loops |
| Task.checkCancellation() | Throws CancellationError if canceled | Check before each step begins |
| group.cancelAll() | Cancel all child tasks in a task group | End early after a timeout or after getting enough results |
@MainActor and UI updates
UIKit and SwiftUI require that UI updates happen on the main thread.
Swift uses the global actor @MainActor (SE-0316, introduced in Swift 5.5) to express "this code belongs to the main thread."
After marking a function or type as @MainActor, calling it from another context requires await, and the compiler handles the thread switch automatically.
Example
import Foundation
@MainActor
func updateUI
(
text
:
String
)
{
(
"Update UI on the main thread: (text)"
)
}
@MainActor
final
class
ViewModel
{
var title
:
String
=
"Loading"
func refresh
(
)
{
title
=
"RUNOOB loaded"
(
title
)
}
}
func demoMainActor
(
)
async
{
await updateUI
(
text
:
"RUNOOB homepage finished loading"
)
let model
=
await ViewModel
(
)
await model.
refresh
(
)
}
await demoMainActor
(
)
Running result:
主线程更新界面:RUNOOB 首页加载完成
RUNOOB 已加载
Marking the entire ViewModel as @MainActor puts all its properties and methods under main-thread management, avoiding crashes caused by background threads modifying the UI.
Do not use @MainActor do time-consuming computation inside a type. Being marked as main-actor doesn't mean "you may freely block the main thread"—expensive parts should be moved to Task and then return to the main thread to update state.
Common questions
Below are the most common questions encountered when getting started with asynchronous programming.
Does await block a thread
No. It merely suspends the current task, releasing the thread to execute other tasks.
What truly blocks a thread is Thread.sleep or synchronous heavy computation; those should be avoided in asynchronous contexts.
What code actually runs on a different thread
Marking something async doesn't by itself guarantee a thread switch; it only allows suspension.
Which thread it runs on is decided by the executor; @MainActor explicitly requires the main thread, while other cases usually fall to the concurrent thread pool.
How to choose between Task and async let
Use Task when you need to break free of the current scope with an independent lifecycle.
To concurrently run a few fixed calls within the current function, use async let; when the count is uncertain, use TaskGroup.
Why is the output order of concurrent tasks different every time
Because completion order is decided by the scheduler, not constrained by the order in code.
When a stable order is needed, either await serially, sort after collecting results, or carry an index in each task and reorder.
Can tasks in a TaskGroup directly modify external variables
No. Task closures are Sendable, and capturing an external mutable variable is rejected by the compiler.
The correct approach is to have each task return a result and collect them in the parent task.
Can an async function be called like a normal function
No. You must use await, and the call site itself must be in an asynchronous context.
For synchronous code to initiate an asynchronous call, it must go through an entry point like Task.