Reputation: 5173
Let's say i have array of any object below , I'm looking for a way to count items in the array as following:
var OSes = ["iOS", "Android", "Android","Android","Windows Phone", 25]
Is there a short way for swift to do something like this below ?
Oses.count["Android"] // 3
Upvotes: 5
Views: 6809
Reputation: 4156
Swift 5 with count(where:)
let countOfAndroid = OSes.count(where: { $0 == "Android" })
Swift 4 or less with filter(_:)
let countOfAndroid = OSes.filter({ $0 == "Android" }).count
Upvotes: 0
Reputation: 72760
A fast, compact and elegant way to do it is by using the reduce
method:
let count = OSes.reduce(0) { $1 == "Android" ? $0 + 1 : $0 }
It's more compact than a for
loop, and faster than a filter
, because it doesn't generate a new array.
The reduce
method takes an initial value, 0 in our case, and a closure, applied to each element of the array.
The closure takes 2 parameters:
The value returned by the closure is used as the first parameter in the next iteration, or as the return value of the reduce
method when the last element has been processed
The closure simply checks if the current element is Android
:
Upvotes: 22
Reputation: 21229
It's pretty simple with .filter
:
OSes.filter({$0 == "Android"}).count // 3
Upvotes: 7