Skip to content

Instantly share code, notes, and snippets.

@swhitty
Last active January 13, 2021 00:20
Show Gist options
  • Save swhitty/0d40457a7dc8a6748066029e999a5dbf to your computer and use it in GitHub Desktop.
Save swhitty/0d40457a7dc8a6748066029e999a5dbf to your computer and use it in GitHub Desktop.
Helper to make concurrent task group with any number of operations
import _Concurrency
extension Task {
// Create group with n tasks, executed concurrently.
// Returned array preserves original order of operations.
static func withGroup<TaskResult>(operations: [() async throws -> TaskResult]) async throws -> [TaskResult] {
return try await Task.withGroup(resultType: (Int, TaskResult).self) { group in
for (idx, provider) in operations.enumerated() {
await group.add {
(idx, try await provider())
}
}
var results: [TaskResult?] = operations.map { _ in nil }
while let (idx, result) = try await group.next() {
results[idx] = result
}
return results.compactMap { $0 }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment