Skip to content

Instantly share code, notes, and snippets.

@jpsim
Created June 11, 2021 15:18
Show Gist options
  • Save jpsim/ec98b46de13842a207fae5b193ae556b to your computer and use it in GitHub Desktop.
Save jpsim/ec98b46de13842a207fae5b193ae556b to your computer and use it in GitHub Desktop.
Parallel map in Swift
extension Array {
func parallelMap<T>(transform: (Element) -> T) -> [T] {
var result = ContiguousArray<T?>(repeating: nil, count: count)
return result.withUnsafeMutableBufferPointer { buffer in
DispatchQueue.concurrentPerform(iterations: buffer.count) { idx in
buffer[idx] = transform(self[idx])
}
return buffer.map { $0! }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment