Concurrency (async/await)
Run async functions, parallelize with async let, and fan out with task groups.
Code
import Foundation
// async function
func fetch(_ url: String) async throws -> String {
try await Task.sleep(nanoseconds: 100_000_000)
return "data from \(url)"
}
// Parallel fetch with async let
func loadAll() async throws -> [String] {
async let a = fetch("https://a.example.com")
async let b = fetch("https://b.example.com")
async let c = fetch("https://c.example.com")
return try await [a, b, c]
}
// Task groups for fan-out work
func sum(_ n: Int) async -> Int {
await withTaskGroup(of: Int.self) { group in
for i in 0..<n {
group.addTask { i * i }
}
var total = 0
for await v in group { total += v }
return total
}
}
// Cancellation
func loop() async {
let task = Task {
for i in 0..<100 {
if Task.isCancelled { print("cancelled"); return }
try? await Task.sleep(nanoseconds: 10_000_000)
}
}
task.cancel()
}
// Top-level await (in async context)
Task {
let results = try await loadAll()
print(results)
print(await sum(5))
await loop()
}Explanation
async/await turns asynchronous code into straight-line reads, suspending at await points without blocking threads. async let runs several awaitables concurrently, and Task groups fan out a dynamic number of child tasks. Tasks support structured cancellation that propagates to children when a parent is cancelled.
More Swift Snippets
Optionals
Use optional binding, nil-coalescing, chaining, and guard for safe unwrapping.
Closures
Define closure expressions, capture state, and pass escaping callbacks.
Protocols
Define contracts, conform with structs, and add default behavior via extensions.
Generics
Write type-parameterized functions and types with protocol constraints.
Structs and Classes
Compare value-type structs with reference-type classes and inheritance.
Error Handling
Throw and catch typed errors with do-catch, try?, try!, and rethrows.