[英]Count number of items in an array with a specific property value
I have a Person() class: 我有一个Person()类:
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() 我有一个Person()数组
var peopleArray = [Person]()
I want to count the number of people in the array who have 我想计算数组中拥有的人数
isManager: true
I feel this is out there, but I can;t find it, or find the search parameters. 我觉得这是在那里,但我无法找到它,或找到搜索参数。
Thanks. 谢谢。
Use filter
method: 使用
filter
方法:
let managersCount = peopleArray.filter { (person : Person) -> Bool in
return person.isManager!
}.count
or even simpler: 甚至更简单:
let moreCount = peopleArray.filter{ $0.isManager! }.count
You can use reduce
as follows: 您可以使用
reduce
如下:
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. reduce
将闭包(第二个参数)应用于数组的每个元素,传递为前一个元素获得的值(或初始值,即作为其第一个参数传递的0
值)和当前数组元素。 In the closure you return count
plus zero or one, depending on whether the isManager property is true
or not. 在闭包中,返回
count
加零或一,取决于isManager属性是否为true
。
More info about reduce
and filter
in the standard library reference 有关标准库参考中的
reduce
和filter
更多信息
count(where:)
was removed from Swift 5 in Xcode 10.2 beta 4. count(where:)
已从Xcode 10.2 beta 4中的Swift 5中删除。
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. 使用Swift 5和Xcode 10.2 beta 3,如果要计算数组中与给定谓词匹配的元素数,可以使用
Array
的count(where:)
方法。 count(where:)
has the following declaration: count(where:)
具有以下声明:
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:)
: 以下Playground示例代码显示了如何使用
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 == true
})
// let managerCount = array.count { $0.isManager } // also works
print(managerCount) // prints: 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.