Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count elements of array matching condition in Swift

Tags:

swift

I'm basically looking for the swift equivalent of the follow c++ code:

std::count_if(list.begin(), list.end(), [](int a){ return a % 2 == 0; }); // counts instances of even numbers in list

My problem isn't actually searching for even numbers, of course; simply the general case of counting instances matching a criterion.

I haven't seen a builtin, but would love to hear that I simply missed it.

like image 223
Aidan Gomez Avatar asked Oct 05 '15 19:10

Aidan Gomez


People also ask

How do you count matching items in an array?

To count the elements in an array that match a condition: Use the filter() method to iterate over the array. On each iteration, check if the condition is met. Access the length property on the array to get the number of elements that match the condition.

How do you find the count of an element in an array in Swift?

In the Swift array, we can count the elements of the array. To do this we use the count property of the array. This property is used to count the total number of values available in the specified array.

How do you check if all elements in an array are true Swift?

Swift has built-in way of checking whether all items in an array match a condition: the allSatisfy() method. Give this thing a condition to check, and it will apply that condition on all items until it finds one that fails, at which point it will return false.


1 Answers

Like this:

 let a: [Int] = ...
 let count = a.filter({ $0 % 2 == 0 }).count
like image 125
Aderstedt Avatar answered Oct 27 '22 19:10

Aderstedt