Skip to content

Instantly share code, notes, and snippets.

@CognitiveDisson
Last active April 29, 2019 14:41
Show Gist options
  • Save CognitiveDisson/ac772024dfd3f00c466ed035b4b0fbbc to your computer and use it in GitHub Desktop.
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(
each: (_ object: Element, _ completion: @escaping () -> (), _ stop: () -> ()) throws -> ()) throws
{
let dispatchGroup = DispatchGroup()
let array = NSArray(array: self)
var eachError: Error?
array.enumerateObjects(options: .concurrent) { obj, key, stop in
guard let object = obj as? Element else {
return
}
dispatchGroup.enter()
do {
try each(
object,
{ dispatchGroup.leave() },
{
stop.pointee = true
dispatchGroup.leave()
}
)
} catch {
eachError = error
stop.pointee = true
dispatchGroup.leave()
}
}
dispatchGroup.wait()
if let error = eachError {
throw error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment