Swift 2 计算数组匹配条件的元素 [英] Swift 2 Count elements of array matching condition

查看:26
本文介绍了Swift 2 计算数组匹配条件的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在寻找以下 C++ 代码的 swift 等效项:

I'm basically looking for the swift equivalent of the follow c++ code:

std::count_if(list.begin(), list.end(), [](int a){ return a % 2 == 0; }); // counts instances of even numbers in list

当然,我的问题实际上并不是搜索偶数;简单地统计匹配一个标准的实例的一般情况.

My problem isn't actually searching for even numbers, of course; simply the general case of counting instances matching a criterion.

我还没有看到内置函数,但很想知道我只是错过了它.

I haven't seen a builtin, but would love to hear that I simply missed it.

推荐答案

像这样:

 let a: [Int] = ...
 let count = a.filter({ $0 % 2 == 0 }).count

这篇关于Swift 2 计算数组匹配条件的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆