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
Imanou petit
source share