The number of elements 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 it is there, but I cannot find it or find the search parameters.

Thanks.

+12
arrays ios swift
source share
3 answers

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 
+22
source share

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 more compact version:

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

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

Read more about reduce and filter in the standard library link

+9
source share

In Swift 5, you can use the Array count(where:) method if you want to count the number of array elements that match a given predicate. count(where:) has the following declaration:

 func count(where predicate: (Element) throws -> Bool) rethrows -> Int 

Returns the number of elements in a sequence that match a given predicate.


The following Playground code shows how to use count(where:) :

 struct Person { var name: String var isManager: Bool init (name: String, isManager: Bool) { self.name = name self.isManager = isManager } } let array = [ Person(name: "Jane", isManager: true), Person(name: "Bob", isManager: false), Person(name: "Joe", isManager: true), Person(name: "Jill", isManager: true), Person(name: "Ted", isManager: false) ] let managerCount = array.count(where: { (person: Person) -> Bool in person.isManager == true }) // let managerCount = array.count { $0.isManager } // also works print(managerCount) // prints: 3 
+1
source share

All Articles