0

I'm trying to create a simple code: I have an "array" with three objects, each containing a boolean value. I would like to create a list that creates a button for each object and when I click on the button, the value of the object switches. I tried but I get an error message: "Cannot assign to property: 'n' is a 'let' constant". Do you have any advice or a simple code for me?

import SwiftUI

struct Object {
   var id = UUID()
   var selected : Bool
}

struct ContentView: View {

   var array = [Object( selected: false), Object(selected: false), Object(selected: false)]

   var body: some View {

       ForEach(array, id: (\.id)) { n in
           VStack {
               Button( action: { n.selected = true }) { Text("Change")}
           }
       }
   }
}

1 Answer 1

3

You can't alter the variable passed in the block because it is immutable. It's just a copy of your list element, it's not your actual list element.

An alternative implementation for what you want that would work is this:

import SwiftUI

struct Object {
    var id = UUID()
    var selected: Bool
}

struct ContentView: View {
    @State var array = [Object(selected: false), Object(selected: false), Object(selected: false)]

    var body: some View {
        ForEach(array.indices) { index in
            VStack {
                Button(action: { self.array[index].selected = true }) {
                    Text("Change: \(self.array[index].selected.description)")
                }
            }
        }
    }
}

I've added the @State decorator that is necessary for you to be able to make changes in the array refresh the view and I've also changed the way we get the value, getting it directly from the array instead of getting it from the param.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.