async/await, Tasks & Actors – Swift
The modern concurrency model: structured concurrency without callback chains.
You mark functions that have to wait (network, file, timer) with async. Callers write await, which is a suspension point: the thread is not blocked but can do other work until the result is available. The code reads like synchronous code.
import Foundation
func ladeZahl(_ n: Int) async -> Int {
try? await Task.sleep(for: .milliseconds(100)) // simulates waiting time
return n * n
}
let a = await ladeZahl(2) // one after another
print(a) // 4
async let b = ladeZahl(3) // starts immediately, in parallel
async let c = ladeZahl(4)
print(await b, await c) // 9 16With a TaskGroup you start any number of child tasks and collect their results. From synchronous code you start work with Task { ... }. Errors flow through throws as usual, called with try await.
let summe = await withTaskGroup(of: Int.self) { gruppe in
for i in 1...5 {
gruppe.addTask { await ladeZahl(i) }
}
var s = 0
for await wert in gruppe { s += wert }
return s
}
print(summe) // 55
func hole(_ url: URL) async throws -> Int {
let (daten, _) = try await URLSession.shared.data(from: url)
return daten.count
}An actor is like a class but protects its mutable state from data races: only one task accesses it at a time. From the outside, its methods are async (await). @MainActor marks code that must run on the main thread (UI).
actor Konto {
private(set) var saldo = 0
func einzahlen(_ betrag: Int) { saldo += betrag }
}
let konto = Konto()
await withTaskGroup(of: Void.self) { gruppe in
for _ in 0..<100 {
gruppe.addTask { await konto.einzahlen(1) }
}
}
print(await konto.saldo) // 100
@MainActor
final class AnsichtsModell {
var titel = "Start"
func aktualisiere() { titel = "Done" } // runs on the main actor
}Sendable marks types that may be safely shared between concurrency domains (value types, actors, immutable classes). With Swift 6 the compiler checks this strictly, turning data races into compiler errors.
task.cancel() sets a flag, and Task.checkCancellation() or try await react to it. You conveniently start a pending Task in a SwiftUI view with the .task { ... } modifier.await does not block the thread, but the code after the await may continue on a different thread, and the state may have changed in the meantime (reentrancy in actors). Never rely on assumptions that held before an await.