How can I sum the money values in the "true" value on the isComplate side?

Viewed 51

I'm just learning the SwiftUI side. Thanks to the code below, I managed to sum all the values. However, I want to sum the money values with "isComplate = True" values. Can you help me?

struct IncomeRow: View {

    //which area where I pull the data
    var todo: TODOS
    
    var body: some View {
        HStack {
            Text(todo.todo)
            Text(todo.category)
            Text("\(todo.money)")
            
            if todo.isComplete == "true" {
                Image(systemName: "checkmark").imageScale(.medium)
            } else {
                Image(systemName: "xmark").imageScale(.medium)
            }
        }
    }
}

//I sum on all values
let totalIncome = self.session.items.map({$0.money}).reduce(0, +) 
let incomePrice = ("$\(totalIncome)")

//isComplate Button Action
func buttonPressed() {
    if complete == true {
        self.complete = false
        self.session.updateTODO(key: todo.key, todo: todo.todo, money: todo.money, isComplete: "false", category: todo.category)
        print("buttonpressed ran, should set complete, complete is: \(String(describing: self.complete))")
    } else {
        self.complete = true
        self.session.updateTODO(key: todo.key, todo: todo.todo, money: todo.money, isComplete: "true", category: todo.category)
        print("buttonpressed ran, should set incomplete, complete is \(String(describing: self.complete))")
    }
} 
1 Answers

You want to use .filter to produce an array of only the completed todos and then sum them. Something like: let completedTodoIncome = self.session.items.filter { $0.isComplete == "true" }.map {$0.money}.reduce(0, +)

It's a bit odd to use a String to represent a true/false (Boolean) value. Better would be to use the Bool type.

Related