Swift: Concurrency – code examples
Using async/await
Concurrency#async#await#async let
Use case: Writing network or database calls without callback nesting.
import Foundation
func ladeNutzer(id: Int) async -> String {
try? await Task.sleep(for: .milliseconds(200))
return "User \(id)"
}
let erster = await ladeNutzer(id: 1)
async let zweiter = ladeNutzer(id: 2)
async let dritter = ladeNutzer(id: 3)
print(erster, await zweiter, await dritter)The first call runs sequentially; async let starts the next two in parallel. Top-level await works in scripts (main.swift).
Running tasks in parallel with TaskGroup
Concurrency#taskgroup#parallel#concurrency
Use case: Running many independent tasks at the same time (downloads, image computations) and collecting the results.
func quadrat(_ n: Int) async -> Int { n * n }
let ergebnisse = await withTaskGroup(of: Int.self) { gruppe in
for i in 1...5 {
gruppe.addTask { await quadrat(i) }
}
var liste: [Int] = []
for await wert in gruppe { liste.append(wert) }
return liste.sorted()
}
print(ergebnisse) // [1, 4, 9, 16, 25]Child tasks run in parallel; their order is unspecified, hence sorted(). The group automatically waits for all children.
Actor for safe state
Concurrency#actor#thread#safety
Use case: Keeping shared mutable state (counters, caches) thread-safe without locks.
actor Zaehler {
private var wert = 0
func increment() -> Int {
wert += 1
return wert
}
var aktuell: Int { wert }
}
let zaehler = Zaehler()
await withTaskGroup(of: Void.self) { gruppe in
for _ in 0..<50 { gruppe.addTask { _ = await zaehler.increment() } }
}
print(await zaehler.aktuell) // 50An actor lets only one caller in at a time. Access from the outside requires await.