Search code examples
iosarraysswift

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


I have a Person() class:

class Person : NSObject {

    var firstName : String
    var lastName : String
    var imageFor : UIImage?
    var isManager : Bool?

    init (firstName : String, lastName: String, isManager : Bool) {
        self.firstName = firstName
        self.lastName = lastName
        self.isManager = isManager
    }
}

I have an array of Person()

var peopleArray = [Person]()

I want to count the number of people in the array who have

 isManager: true

I feel this is out there, but I can;t find it, or find the search parameters.

Thanks.


Solution

  • 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