Count number of items in an array with a specific property value

Use filter method:

let managersCount = peopleArray.filter { (person : Person) -> Bool in
    return person.isManager!
}.count

or even simpler:

let moreCount = peopleArray.filter{ $0.isManager! }.count

You can use reduce as follows:

let count = peopleArray.reduce(0, combine: { (count: Int, instance: Person) -> Int in
    return count + (instance.isManager! ? 1 : 0) }
)

or a more compact version:

let count = peopleArray.reduce(0) { $0 + ($1.isManager! ? 1 : 0) }

reduce applies the closure (2nd parameter) to each element of the array, passing the value obtained for the previous element (or the initial value, which is the 0 value passed as its first parameter) and the current array element. In the closure you return count plus zero or one, depending on whether the isManager property is true or not.

More info about reduce and filter in the standard library reference

Tags:

Arrays

Ios

Swift