× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

how to count specific items in array in swift

Antonio Bello
Jul 06, 2015
<p>A fast, compact and elegant way to do it is by using the <code>reduce</code> method:</p> <pre><code>let count = OSes.reduce(0) { $1 == "Android" ? $0 + 1 : $0 } </code></pre> <p>It's more compact than a <code>for</code> loop, and faster than a <code>filter</code>, because it doesn't generate a new array.</p> <p>The <code>reduce</code> method takes an initial value, 0 in our case, and a closure, applied to each element of the array.</p> <p>The closure takes 2 parameters:</p> <ul> <li>the value at the previous iteration (or the initial value, 0 in our case)</li> <li>the array element for the current iteration</li> </ul> <p>The value returned by the closure is used as the first parameter in the next iteration, or as the return value of the <code>reduce</code> method when the last element has been processed</p> <p>The closure simply checks if the current element is <code>Android</code>: </p> <ul> <li>if not, it returns the aggregate value (the first parameter passed to the closure)</li> <li>if yes, it returns that number plus one</li> </ul> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31194938/how%20to%20count%20specific%20items%20in%20array%20in%20swift/31195177">Stack Overflow</a>.</p>
comments powered by Disqus