Skip to content

Instantly share code, notes, and snippets.

@CognitiveDisson
Last active April 29, 2019 14:41
Show Gist options
  • Select an option

  • Save CognitiveDisson/ac772024dfd3f00c466ed035b4b0fbbc to your computer and use it in GitHub Desktop.

Select an option

Save CognitiveDisson/ac772024dfd3f00c466ed035b4b0fbbc to your computer and use it in GitHub Desktop.
Swift: Async concurrent enumerated array
import Foundation
public extension Array {
public func asyncConcurrentEnumerated<T>(
each: (_ object: T, _ completion: (Bool) -> ()) throws -> ()) -> Error?
{
let dispatchGroup = DispatchGroup()
let array = NSArray(array: self)
var eachError: Error?
array.enumerateObjects(options: .concurrent) { obj, key, stop in
guard let object = obj as? T else {
return
}
dispatchGroup.enter()
do {
try each(
object,
{ stopValue in
if stopValue == true {
stop.pointee = true
}
dispatchGroup.leave()
}
)
} catch {
eachError = error
stop.pointee = true
dispatchGroup.leave()
}
}
dispatchGroup.wait()
return eachError
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment