Collection.swift 987 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. //
  2. // Collection.swift
  3. // LoopKit
  4. //
  5. // Created by Michael Pangburn on 12/4/18.
  6. // Copyright © 2018 LoopKit Authors. All rights reserved.
  7. //
  8. import Dispatch
  9. import LoopKit
  10. extension Collection {
  11. func asyncMap<NewElement>(
  12. _ asyncTransform: (
  13. _ element: Element,
  14. _ completion: @escaping (NewElement) -> Void
  15. ) -> Void,
  16. notifyingOn queue: DispatchQueue = .global(),
  17. completion: @escaping ([NewElement]) -> Void
  18. ) {
  19. let result = Locked(Array<NewElement?>(repeating: nil, count: count))
  20. let group = DispatchGroup()
  21. for (resultIndex, element) in enumerated() {
  22. group.enter()
  23. asyncTransform(element) { newElement in
  24. result.value[resultIndex] = newElement
  25. group.leave()
  26. }
  27. }
  28. group.notify(queue: queue) {
  29. let transformed = result.value.map { $0! }
  30. completion(transformed)
  31. }
  32. }
  33. }