How to count specific elements in an array in swift

Let's say I have an array of any object below, I am looking for a way to count the elements in an array like this:

var OSes = ["iOS", "Android", "Android","Android","Windows Phone", 25]

      

Is there a short way to quickly do something like this below?

Oses.count["Android"]   // 3 

      

+3


source to share


3 answers


A fast, compact and elegant way to do it with the method reduce

:

let count = OSes.reduce(0) { $1 == "Android" ? $0 + 1 : $0 }

      

It's more compact than a loop for

and faster than a loop filter

because it doesn't generate a new array.

The method reduce

takes an initial value, 0 in our case, and a closure applied to each element in the array.

The closure has 2 parameters:



  • the value at the previous iteration (or the initial value, 0 in our case)
  • array element for the current iteration

The value returned by the closure is used as the first parameter in the next iteration, or as the return value of the method reduce

when the last element has been processed

The closure just checks if the current element is Android

:

  • if not, it returns the aggregated value (the first parameter passed to the closure)
  • if yes it returns that number plus one
+16


source


It's pretty simple with .filter

:



OSes.filter({$0 == "Android"}).count // 3

      

+4


source


Swift 5 with score (where :)

let countOfAndroid = OSes.count(where: { $0 == "Android" })

      

Swift 4 or less with filter (_ :)

let countOfAndroid = OSes.filter({ $0 == "Android" }).count 

      

0


source







All Articles