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.
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.
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.
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.
Like this:
let a: [Int] = ...
let count = a.filter({ $0 % 2 == 0 }).count
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With