Skip to content

Instantly share code, notes, and snippets.

@CognitiveDisson
Created February 12, 2019 13:39
Show Gist options
  • Save CognitiveDisson/bb88b26262b49b3c78a2ad737024a373 to your computer and use it in GitHub Desktop.
Save CognitiveDisson/bb88b26262b49b3c78a2ad737024a373 to your computer and use it in GitHub Desktop.
ConcurrentPerformer
import Foundation
final class ConcurrentPerformer {
func perform<T>(_ objects: [T], iterations: Int? = nil, action: ((T) -> ())) {
if let iterations = iterations {
customPerform(objects, iterations: iterations, action: action)
} else {
defaultPerform(objects, action: action)
}
}
private func defaultPerform<T>(_ objects: [T], action: ((T) -> ())) {
let array = objects as NSArray
array.enumerateObjects(options: .concurrent) { obj, _, _ in
if let obj = obj as? T {
action(obj)
}
}
}
private func customPerform<T>(_ objects: [T], iterations: Int, action: ((T) -> ())) {
let objectsPerIteration = Int(objects.count / iterations) + 1
DispatchQueue.concurrentPerform(iterations: iterations) { index in
for index in index * objectsPerIteration ..< (index + 1) * objectsPerIteration {
guard index < objects.count else { continue }
let object = objects[index]
action(object)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment