【问题标题】:How can I sum the money values in the "true" value on the isComplate side?如何在 isComplate 端的“真实”价值中总结货币价值?
【发布时间】:2021-03-10 17:04:42
【问题描述】:

我只是在学习 SwiftUI 方面。感谢下面的代码,我设法对所有值求和。但是,我想将货币值与“isComplate = True”值相加。你能帮帮我吗?

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))")
    }
} 

【问题讨论】:

  • 在 Stack Overflow 上,请不要显示文字和代码的图片。将文本复制到问题本身并设置格式,以便于阅读、复制和搜索。
  • @DougStevenson 感谢您的反馈。我修好了。
  • map(\.money)。顺便说一句Bool 有一个切换方法self.complete.toggle()
  • 为什么这个问题用 Firebase 标记。我没有看到任何提及。

标签: swift firebase swiftui


【解决方案1】:

您想使用.filter 生成仅包含已完成待办事项的数组,然后对它们求和。比如:let completedTodoIncome = self.session.items.filter { $0.isComplete == "true" }.map {$0.money}.reduce(0, +)

使用字符串来表示真/假(布尔)值有点奇怪。最好使用Bool type

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多