Last active
April 29, 2019 14:41
-
-
Save CognitiveDisson/ac772024dfd3f00c466ed035b4b0fbbc to your computer and use it in GitHub Desktop.
Swift: Async concurrent enumerated array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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