Created
February 12, 2019 13:39
-
-
Save CognitiveDisson/bb88b26262b49b3c78a2ad737024a373 to your computer and use it in GitHub Desktop.
ConcurrentPerformer
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 | |
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