查找数组中符合条件的行总数 | Swift

Finding the count of the total amount of rows that meet criteria in array | Swift

基本上我有一个表视图,其中的行使用 JSON 填充,结构如下:

struct Section {
    let name : String
    var items : [Portfolio]
}

struct Portfolio: Decodable {

    let person: String
    let number: String
    var checking: Int

    enum CodingKeys : String, CodingKey {
        case customer, serial, checking
    }

}

检查的值可以是1或0

我如何计算 checking = 1 的总行数?

目前我正在尝试做这样的事情,但我不确定这是否朝着正确的方向前进:

let item = sections[indexPath.section].items[indexPath.row]
let a = item.checking
let count = a.filter({ [=12=] % 2 == 0 }).count

您需要(如果对于所有部分)

let total = sections.map { [=10=].items.filter { [=10=].checking == 1 }.count }.reduce(0,+)

如果针对特定部分

let total = sections[indexpath.section].items.filter { [=11=].checking == 1 }.count 

这是你可以做到的

func totalItems(_ sections: [Section]) -> Int {
  return sections.reduce(0) { [=10=] + .items.filter{ [=10=].checking == 1 }.count }
}