如何快速计算数组中的特定项目 [英] how to count specific items in array in swift
问题描述
假设我在下面有任何对象的数组,我正在寻找一种方法来对数组中的项目进行计数,如下所示:
Let's say i have array of any object below , I'm looking for a way to count items in the array as following:
var OSes = ["iOS", "Android", "Android","Android","Windows Phone", 25]
有没有一种快速的方法可以在下面快速执行以下操作?
Is there a short way for swift to do something like this below ?
Oses.count["Android"] // 3
推荐答案
一种快速,紧凑且优雅的方法是使用reduce
方法:
A fast, compact and elegant way to do it is by using the reduce
method:
let count = OSes.reduce(0) { $1 == "Android" ? $0 + 1 : $0 }
它比for
循环更紧凑,并且比filter
更快,因为它不会生成新的数组.
It's more compact than a for
loop, and faster than a filter
, because it doesn't generate a new array.
reduce
方法采用一个初始值(在我们的情况下为0),并且将闭包应用于数组的每个元素.
The reduce
method takes an initial value, 0 in our case, and a closure, applied to each element of the array.
闭包采用2个参数:
- 上一次迭代的值(或初始值,本例中为0)
- 当前迭代的数组元素
闭包返回的值用作下一次迭代中的第一个参数,或在处理完最后一个元素时用作reduce
方法的返回值
The value returned by the closure is used as the first parameter in the next iteration, or as the return value of the reduce
method when the last element has been processed
闭包仅检查当前元素是否为Android
:
The closure simply checks if the current element is Android
:
- 如果不是,则返回合计值(传递给闭包的第一个参数)
- 如果是,它将返回该数字加一个
这篇关于如何快速计算数组中的特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!