You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计Swift动态列表中特定属性的数量?以isTaken属性为例

统计Swift数组中isTaken属性的数量

原始数据代码

@Published var storedMedicines: [Medicine] = [
    Medicine(Title: "Medicine 1", Description: "Lower blood sugar", date: .init(timeIntervalSince1970: 1664779248), isTaken: false),
    Medicine(Title: "Medicine 1", Description: "Lower blood sugar", date: .init(timeIntervalSince1970: 1664880248), isTaken: false),
    Medicine(Title: "Medicine 1", Description: "Lower blood sugar", date: .init(timeIntervalSince1970: 1664720990), isTaken: false),
    Medicine(Title: "Medicine 1", Description: "Lower blood sugar", date: .init(timeIntervalSince1970: 1664720990), isTaken: false),
]

实现方法

方法1:两次filter统计

通过filter分别筛选出isTaken为true和false的元素,再获取对应数量:

let takenCount = storedMedicines.filter { $0.isTaken }.count
let notTakenCount = storedMedicines.filter { !$0.isTaken }.count
print("\(takenCount)个isTaken为true,\(notTakenCount)个isTaken为false")

方法2:单次reduce统计(更高效)

用reduce遍历一次数组同时统计两种状态的数量,避免多次遍历数组,适合元素较多的场景:

let countResult = storedMedicines.reduce((taken: 0, notTaken: 0)) { accumulator, medicine in
    medicine.isTaken 
        ? (taken: accumulator.taken + 1, notTaken: accumulator.notTaken)
        : (taken: accumulator.taken, notTaken: accumulator.notTaken + 1)
}
print("\(countResult.taken)个isTaken为true,\(countResult.notTaken)个isTaken为false")

内容的提问来源于stack exchange,提问作者Gem12345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:01:07