How do I count the unique values in an array?

I have an array with 200 items in it. They are a combination of true and false values. I would like to count the number of ‘true’ and the number of ‘false’.

I know how to count the total number of items in the array but I do not know how to tally the different values and would appreciate some help on this.


A brute forcey way, which would not be ideal for anything other than booleans:

var numTrue = 0
var numFalse = 0
for value in values {
if value {
numTrue += 1
else {
numFalse += 1


Or you can try using NSCountedSet.

let set = NSCountedSet()
for value in values {
debugPrint(set.count(for: true))
debugPrint(set.count(for: false))

You can use some of the Array high order functions to do so. The following examples are made with the assumption of a Boolean array :

reduce(_: _:slight_smile:
Returns the result of combining the elements of the sequence using the given closure.

let trueCount = myArray.reduce(0) { (res, val) -> Int in
    return res + (val ? 1 : 0)

How it works : First, we set an initial value, here 0 (since the counting starts from 0). Then we iterate through the array, with a closure. This closure takes for parameter the result of the previous iteration (or the initial value for the first iteration), and the value of the array for the current iteration. So basically you just want to returns your sum incremented if the value is true, otherwise you don’t increment the sum.

Returns the elements of self that satisfy predicate.

let trueCount = myArray.filter {$0}.count

Here you create a new array from your original array with filter, and get the number of values on it. The elements of the original array passing the predicate are added to the new array. Since the initial array is made of Boolean, the predicate is simply the value tested, which can be expressed using $0.

For the total of false value, just use myArray.count - trueCount

Thank you both for your thoughtful and detailed responses. Much appreciated.