【问题标题】:Finding the count of the total amount of rows that meet criteria in array | Swift查找数组中满足条件的总行数|迅速
【发布时间】:2020-05-05 23:37:49
【问题描述】:

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

【问题讨论】:

    标签: ios swift uitableview codable


    【解决方案1】:

    你可以这样做

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

    【讨论】:

      【解决方案2】:

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

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

      如果针对特定部分

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

      【讨论】:

      猜你喜欢
      • 2021-05-27
      • 2021-02-01
      • 2013-10-19
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2020-05-11
      相关资源
      最近更新 更多