Code
swift
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()
}