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

前端 未结 3 1536
无人共我
无人共我 2021-02-18 18:36

I have a Person() class:

class Person : NSObject {

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

          


        
3条回答
  •  执念已碎
    2021-02-18 18:57

    count(where:) was removed from Swift 5 in Xcode 10.2 beta 4.


    With Swift 5 and Xcode 10.2 beta 3, you can use Array's count(where:) method if you want to count the number of elements in an array 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 the sequence that satisfy the given predicate.


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

    struct Person {
        let name: String
        let isManager: Bool
    }
    
    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
        return person.isManager
    })
    // let managerCount = array.count { $0.isManager } // also works
            
    print(managerCount) // prints: 3
    

提交回复
热议问题