Async/await with a task group in Swift

Swift

Runs the downloads concurrently and collects them, with cancellation propagating to all of them.

func loadAll(_ urls: [URL]) async throws -> [Data] {
    try await withThrowingTaskGroup(of: Data.self) { group in
        for url in urls {
            group.addTask { try await URLSession.shared.data(from: url).0 }
        }
        var results: [Data] = []
        for try await data in group { results.append(data) }
        return results
    }
}

More in Systems

Random picks