The following code can be found at https://www.swiftbysundell.com/articles/async-and-concurrent-forEach-and-map/. The concurrentMap function is the concurrent version of map. It executes multiple operations in parallel and returns the results in the original order.
extension Sequence {
func asyncMap<T>(
_ transform: (Element) async throws -> T
) async rethrows -> [T] {
var values = [T]()
for element in self {
try await values.append(transform(element))
}
return values
}
func concurrentMap<T>(
_ transform: @escaping (Element) async throws -> T
) async throws -> [T] {
let tasks = map { element in
Task {
try await transform(element)
}
}
return try await tasks.asyncMap { task in
try await task.value
}
}
}
I don't understand how the concurrentMap function works.
Why is it executed in parallel?
In the asyncMap, it does try await values.append(transform(element))
, so it looks like it waits for each process. But in fact they are executed in parallel.
I have confirmed that the concurrentMap function is working correctly, but I don't understand why this is happening, so I would appreciate an explanation.