swiftuiswiftui-listdynamic-list

How to count the specific item in dynamic list?


@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),
]

I want to know how can I count the "isTaken" attribute in here. I want to specifically make it said that "2 isTaken true" and 2 isTaken false"


Solution

  • There are two many ways to do this.

    Using filter.

    let trueCount = storedMedicines.filter(\.isTaken).count
    let falseCount = storedMedicines.count - trueCount
    

    Using reduce.

    let trueCount = storedMedicines.reduce(0, { $0 + ($1.isTaken ? 1 : 0) })
    let falseCount = storedMedicines.count - trueCount