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

前端 未结 3 1528
无人共我
无人共我 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:48

    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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-18 19:06

    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

    0 讨论(0)
提交回复
热议问题