ConcurrentMap.swift 634 B

12345678910111213141516171819
  1. import Foundation
  2. extension Collection where Index == Int {
  3. func concurrentMap<T>(_ transform: (Element) -> T) -> [T] {
  4. let buffer = UnsafeMutableRawPointer.allocate(
  5. byteCount: count * MemoryLayout<T>.stride,
  6. alignment: MemoryLayout<T>.alignment
  7. ).bindMemory(to: T.self, capacity: count)
  8. DispatchQueue.concurrentPerform(iterations: count) { index in
  9. let element = self[index]
  10. let transformedElement = transform(element)
  11. buffer[index] = transformedElement
  12. }
  13. return [T](UnsafeBufferPointer(start: buffer, count: count))
  14. }
  15. }