Swift Concurrency
Apps constantly wait: for the network, for a file, for a database. Swift's built-in concurrency model lets you write that waiting code in a straight line with async and await, run work in parallel with async let and task groups, and protect shared state with actors — all checked by the compiler.
async and await
A function marked async can suspend: pause while it waits for something, letting the thread do other work in the meantime. You call it with await, which marks every point where suspension may happen.
func fetchUsername(id: Int) async -> String {
// Pretend this talks to a server
try? await Task.sleep(nanoseconds: 10_000_000) // 10 ms
return id == 1 ? "ada" : "guest"
}
print("Loading…")
let name = await fetchUsername(id: 1)
print("Hello, \(name)!")Loading…
Hello, ada!
In a top-level script (like this playground) you may use await directly. In an app you call async code from another async function or from a Task.
| Keyword | Where | Meaning |
|---|---|---|
async |
function declaration | "this function may suspend" |
await |
call site | "execution may pause here" |
throws / try |
combined with async |
async functions can throw too: async throws / try await |
Async functions that throw
Network calls fail, so async functions are often also throws. The order is always async throws in the declaration and try await at the call:
enum NetworkError: Error {
case notFound
}
func loadPrice(for item: String) async throws -> Double {
let catalog = ["apple": 0.5, "bread": 2.25]
guard let price = catalog[item] else { throw NetworkError.notFound }
return price
}
for item in ["bread", "caviar"] {
do {
let price = try await loadPrice(for: item)
print("\(item): \(price)")
} catch {
print("\(item): \(error)")
}
}bread: 2.25
caviar: notFound
Running work in parallel with async let
Plain await runs calls one after another. With async let you start several child tasks immediately and await their results later — they run concurrently.
func download(_ file: String, size: Int) async -> Int {
try? await Task.sleep(nanoseconds: UInt64(size) * 1_000_000)
return size
}
async let a = download("photo.jpg", size: 30)
async let b = download("song.mp3", size: 20)
async let c = download("notes.txt", size: 5)
let total = await a + b + c
print("Downloaded \(total) MB in parallel")Downloaded 55 MB in parallel
The three downloads overlap, so the whole thing takes about as long as the slowest one, not the sum.
Task groups
When the number of child tasks is only known at run time, use a task group. Results arrive in completion order, so combine them in an order-independent way (sum them, or sort them) before printing:
func square(_ n: Int) async -> (Int, Int) {
(n, n * n)
}
let results = await withTaskGroup(of: (Int, Int).self) { group in
for n in 1...5 {
group.addTask { await square(n) }
}
var collected: [(Int, Int)] = []
for await pair in group {
collected.append(pair)
}
return collected.sorted { $0.0 < $1.0 }
}
for (n, sq) in results {
print("\(n)² = \(sq)")
}1² = 1
2² = 4
3² = 9
4² = 16
5² = 25
Task: starting async work
Task { … } creates a new top-level task. You can await its value to get the result, or cancel it with task.cancel().
// In an app, e.g. a button action (not async itself):
Button("Refresh") {
Task {
let items = await api.loadItems()
self.items = items
}
}Actors: safe shared state
If two tasks change the same variable at the same time you get a data race. An actor is like a class whose mutable state can only be touched by one task at a time. From outside, every access needs await:
actor BankAccount {
private(set) var balance = 0
func deposit(_ amount: Int) {
balance += amount
}
}
let account = BankAccount()
await withTaskGroup(of: Void.self) { group in
for _ in 1...100 {
group.addTask { await account.deposit(10) }
}
}
print("Balance:", await account.balance)Balance: 1000
Even though 100 tasks deposit concurrently, the actor serializes the calls, so the balance is always exactly 1000.
Note: In SwiftUI apps, UI code runs on the main actor (
@MainActor). Mark view models with@MainActorso their properties are only updated on the main thread.
Tip: Swift 6 turns on strict concurrency checking: the compiler refuses code that could cause a data race, such as sharing a non-
Sendableclass between tasks.
Test yourself
How do you call a function declared func load() async throws -> Data?
- await try load()
- try await load()
- async load()
- try load() async
What is the main benefit of async let?
- It makes a constant mutable
- It starts child tasks that run concurrently and are awaited later
- It cancels all other tasks
- It runs code on the main thread
Why does accessing an actor's property from outside need await?
- Actors are always on another computer
- The actor may be busy, so the caller might have to wait its turn
- Properties of actors are optional
- It is only needed for
letproperties