Skip to content

Instantly share code, notes, and snippets.

@alextrob alextrob/Array+Concurrency.swift Secret
Last active Jun 2, 2020

Embed
What would you like to do?
Multi-core for-each and map
public extension Array {
/// Synchronous
func concurrentMap<T>(transform: @escaping (Element) -> T) -> [T] {
let result = UnsafeMutablePointer<T>.allocate(capacity: count)
DispatchQueue.concurrentPerform(iterations: count) { i in
result.advanced(by: i).initialize(to: transform(self[i]))
}
let finalResult = Array<T>(UnsafeBufferPointer(start: result, count: count))
result.deallocate()
return finalResult
}
/// Synchronous
func concurrentForEach(action: @escaping (Element) -> Void) {
_ = concurrentMap { _ = action($0) }
}
}
// Works just like regular `map` and `forEach`.
// This is a simple example to show API usage; don't actually use this for such tiny amounts of work.
let things = [1, 2, 3, 4]
// 1
// 2
// 3
// 4
things.concurrentForEach {
print($0)
}
let multipliedByTwo = things.concurrentMap { $0 * 2 } // [2, 4, 6, 8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.