如何在数组中计算一些时间"是" ?在快速
createObject
例如这里有3次 谢谢;)
答案 0 :(得分:3)
这样的事情怎么样?
//: Playground - noun: a place where people can play
import UIKit
let array = ["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]
let results = array.map({ $0.lowercaseString.containsString("yes") })
let count = results.filter({ $0 == true }).count
count // 3
你也可以把它变成一个班轮:
let count = array.filter({ $0.lowercaseString.containsString("yes") }).count
注意:我还添加了一个区分大小写的检查,只是因为数据源不一致
答案 1 :(得分:2)
let a = ["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]
let filtered = a.filter { (str) -> Bool in
return str.containsString("Yes")
}
print(filtered.count)
答案 2 :(得分:2)
let array = ["julien: Yes","elie: Yes", "Mark: No", "Jean: Yes"]
let count = array.reduce(0) { $0 + ($1.containsString("Yes") ? 1 : 0) }
count // 3
答案 3 :(得分:1)
您可以使用NSPredicate获取所需的输出,如下所示
var arrayTemp = NSMutableArray(objects: "julien: Yes","elie: YES", "elie: NO", "Jean: Yes")
var predicate = NSPredicate(format: "self contains[cd] %@", "Yes")
arrayTemp.filterUsingPredicate(predicate)
print("COUNT===\(arrayTemp.count)")// 3