I'd like to calculate and display the total expenses that the user inputs into the app. I think a computed property called totalExpense
within the contentView is the right approach, but I'm stuck on how to do this calculation.
Below is some preliminary background. If this is not enough info, I'll share my github repository at the end of the message.
Background
Within the iExpense project, I have a struct, which defines each expense item:
struct ExpenseItem: Identifiable, Codable, Equatable {
let id = UUID()
let name: String
let type: String
let amount: Double
}
Then I have a class, which is an array of expenseItems
class ExpenseArray: ObservableObject {
@Published var items = [ExpenseItem]() {
didSet {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(items) {
UserDefaults.standard.set(encoded, forKey: "Items")
}
}
}
// (See full code in github)
I'm thinking of creating a computed property within my contentView, but this is where I get stuck.
@State private var totalExpenses: Double {
// perform calculation for total expenses using class??
}
Appreciate any help on this!
Github repo: (see lines 14 and 26 in ContentView):
https://github.com/iosPit/ExpenseTracker