How to modify attributes of class inside ForEach?

I'm trying to change the attribute of points by adding 1 every time the button is pressed, however, it does not change. How could I accomplish this?

   
   
  class Person{
     
    var name = ""
    var points = 0
  }
  var Greg = Person()
  var Jeo = Person()
  var Humio = Person()
   
  init(Greg: Person = Person(), Jeo: Person = Person(), Humio: Person = Person()) {
    self.Greg = Greg
    self.Jeo = Jeo
    self.Humio = Humio
     
    Greg.name = "Greg"
    Jeo.name = "Jeo"
    Humio.name = "Humio"
  }
   
   
  var body: some View {
     
    var nombres:[Person] = [Greg, Jeo, Humio]
    
    VStack {
      ForEach(nombres, id: \.name){
        names in
         
        ZStack{
          Rectangle()
           .frame(width: 200, height: 200)
          VStack{
            Text("\(names.points)")
              .foregroundColor(Color.white)
             
            Button(action: {
               
              names.points += 1
               
            }, label: {
               
              Text(names.name)
               
            })
             
          }
           
        }
         
      }
    }
    .padding()
  }
}

Does your code compile ?

  • I do not see where you use your init.
  • you have no ContentView defined
  • also note that var names should start with lowerCase

You also need to have a state var that changes to force redraw.

I did this with the trick of update and use the always true if update || !update { }

There is certainly a cleaner way to do it, but this shows how to make it work.

class Person {
   
  var name = ""
  var points = 0
    
    init(name: String) {
        self.name = name
    }
}

struct ContentView: View {
    
    let greg = Person(name: "Greg")
    let jeo = Person(name: "Jeo")
    let humio = Person(name: "Humio")
    @State var update = false
    
    var nombres: [Person] {
        [greg, jeo, humio]
    }

    var body: some View {
        
        VStack {
            ForEach(nombres, id: \.name){ names in
                ZStack{
                    Rectangle()
                        .frame(width: 200, height: 200)
                    VStack{
                        if update || !update {  // A trick to have the View react to a change of state !
                            Text("\(names.points)")
                                .foregroundColor(Color.white)
                        }
                        
                        Button(action: {
                            names.points += 1
                            update.toggle()  // To change value of the state var
                        }, label: {
                            Text(names.name)
                        })
                        
                    }
                    
                }
                
            }
        }
        .padding()
    }
}

How to modify attributes of class inside ForEach?
 
 
Q