0

I'm trying to declare Array with a @Published var property. However, the value is never updated (Always the default -> 0).

How can I do that ? What am I doing wrong ?

Thank you very much for your help ;)

Have a nice day

struct MyCategory: Identifiable, Hashable {
    let id = UUID()
    let name: String
    let amount: Double
}

class MyViewModel: ObservableObject {
    
    @Published var amount1: Double = 0
    @Published var amount2: Double = 0
    @Published var categories = [MyCategory]()
    
    init() {
        self.categories = [
            MyCategory(name: "Test 1", amount: self.amount1),
            MyCategory(name: "Test 2", amount: self.amount2)
        ]
    }

    func updateAmounts(value1: Double, value2: Double) {
        self.amount1 += value1
        self.amount2 += value2
    }
}
    
import SwiftUI

struct MyView: View {
    
    @EnvironmentObject var myViewModel: MyViewModel
    
    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            ForEach(myViewModel.categories, id: \.self) { category in
                HStack() {
                     Text("\(category.name)")
                     Text("\(category.amount)") // Value not refresh! 0
                }
            }
        }
    }
}
Chéramy Alexandre
  • 444
  • 3
  • 8
  • 25
  • 1
    When/how do you update the amount? _Edit_ If you think the updateAmouns function will update the objects in the array then that is not correct. The objects in the array holds their own copy of the amount – Joakim Danielson Aug 15 '21 at 09:26
  • The update amount function is launch from an another action button (Values come from Firestore database) Yes I wish update the objects in the array or something like that. Do you know how I can do that ? – Chéramy Alexandre Aug 15 '21 at 09:42
  • Maybe something like [this](https://stackoverflow.com/questions/61843178/how-can-i-toggle-a-property-of-an-object-in-an-array-and-update-the-swiftui-view) – Joakim Danielson Aug 15 '21 at 09:44

0 Answers0