Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seyhunak/14b5fa3ad54dfaeb727d5be9a21ff291 to your computer and use it in GitHub Desktop.
Save seyhunak/14b5fa3ad54dfaeb727d5be9a21ff291 to your computer and use it in GitHub Desktop.
DispatchGroup convenience wrapper for executing a series of blocks concurrently
import Foundation
extension DispatchGroup {
/// Completes a series of blocks and finally executes a completion handler.
///
/// - Parameters:
/// - label: An optional DispatchQueue label (defaults to bg)
/// - qos: An optional DipatchQos (defaults to background)
/// - blocks: The series of blocks to call.
/// - completion: The final completion handler when all blocks are
/// finished.
///
/// Ensure you call the completion handler in every block.
func complete(
label: String = "bg",
qos: DispatchQoS = .background,
_ blocks: ((() -> Void) -> Void)...,
completion: @escaping () -> Void) {
for block in blocks {
self.enter()
DispatchQueue(
label: label,
qos: qos).async {
block({
self.leave()
})
}
}
self.notify(queue: .main) {
completion()
}
}
}
// MARK: - Example
DispatchGroup().complete(
{ completion in sleep(1); print("execution 1"); completion() },
{ completion in print("execution 2"); completion() },
{ completion in print("execution 3"); completion() }
) {
print("end of group completion handler")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment