<html><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class="">I had the need for a concurrent map recently. I had a part of a program which needed to read chunks of data and concurrently process them and assemble the results in an array. This isn’t necessarily as obvious as it sounds, because of arrays being value types. I came up with the following snippet which I’d like to check for correctness; it could also be helpful to others.<div class=""><br class=""></div><div class="">Perhaps this is something Dispatch should provide out-of-the-box?</div><div class=""><br class=""></div><div class="">- Karl</div><div class=""><br class=""></div><div class=""><br class=""></div><blockquote style="margin: 0 0 0 40px; border: none; padding: 0px;" class=""><div class="">extension DispatchQueue {</div><div class=""><br class=""></div><div class=""> static func concurrentMap<T>(iterations: Int, execute block: (Int) -> T) -> [T] {</div><div class=""> var result = Array<T>()</div><div class=""> result.reserveCapacity(iterations)</div><div class=""><br class=""></div><div class=""> result.withUnsafeMutableBufferPointer { (results: inout UnsafeMutableBufferPointer<T>) in</div><div class=""> concurrentPerform(iterations: iterations) { idx in</div><div class=""> results[idx] = block(idx)</div><div class=""> }</div><div class=""> }</div><div class=""><br class=""></div><div class=""> return result</div><div class=""> }</div><div class="">}</div><div class=""><br class=""></div><div class="">extension Array {</div><div class=""> func concurrentMap<T>(execute block: (Element)->T) -> [T] {</div><div class=""> return DispatchQueue.concurrentMap(iterations: count) { block(self[$0]) }</div><div class=""> }</div><div class="">}</div></blockquote></body></html>