Home > Blockchain >  swiftui: problem with adding a property to data struct
swiftui: problem with adding a property to data struct

Time:01-09

I have a struct:

struct Property: Identifiable, Codable, Hashable {
    var id = UUID()
    var name : String = ""
    var symbol : String = PropertySymbols.randomName()
    var address: String?
    var propertyArea: String?
    var meters : [Meter] = [Meter(name: "electricity"), Meter(name: "water")]
    
}

struct Meter: Identifiable, Hashable, Codable {
    var id = UUID()
    var name : String = ""
}

class PropertyData: ObservableObject {
    @Published var properties: [Property] = [
    Property(name: "Saks 85/1", meters: [Meter(name: "electricity")]),
    Property(name: "Saks 85/2", meters: [Meter(name: "electricity"), Meter(name: "water")]),
    Property(name: "Saks 85/3", meters: [Meter(name: "electricity"), Meter(name: "cold water"), Meter(name: "hot water")]),
    ]
}

@ObservedObject var data : PropertyData
    var property : Property
    @State var newMeter: String = ""
    @Environment(\.presentationMode) var presentationMode
    
    
    var body: some View {
        VStack {
            Form{
                Section {
                    TextField("Add another meter", text: $newMeter)
                    Button{
                        if newMeter != "" {
                            property.meters.append(Meter(name: newMeter))    //THAT IS THE PROBLEM
                            print(property.meters.count)
                        }
                    } label: {
                        Text("Add a meter")
                    }.centerHorizontally()
                }
                ForEach(0..<property.meters.count, id:\ .self) {index in
                    Text(property.meters[index].name)
                }
                Section() {
                    Button("That's enough"){
                        print(property.meters)
                        presentationMode.wrappedValue.dismiss()}.centerHorizontally()
                }
            }
        }
    }
}

when in ContentView I try

apartment.meter.append(Meter(name:"water")) I get

Cannot use mutating member on immutable value: 'self' is immutable

Can't get through that, tried @State and @Binding etc, it doesn't work, if I try as make @State var property - it changes here, but doesn't update the data...

CodePudding user response:

Guessing here but var property : Property should be

@Binding var property : Property

let means that the variable won't change. @Binding is a two-way connection.

You will connect them in your previous view with something like this.

ForEach($data.properties, id:\.id){ $property 
    YourViewName(property: $property)
}

This question marks denote the two-way connection. Without them you are not going to be able to change the variable.

  •  Tags:  
  • Related