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

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

提交回复
热议问题