首页 > 解决方案 > 查找数组中满足条件的总行数| 迅速

问题描述

本质上,我有一个表视图,其中的行使用 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

如何计算检查 = 1 的总行数?

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

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

标签: iosswiftuitableviewcodable

解决方案


这是你如何做到的

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

推荐阅读