3

I am trying to create an array which contains my struct Element. Trying to use .append I get two errors.

"Cannot use mutating member on immutable value: 'self' is immutable" and "Cannot convert value of type 'Element' to expected argument type '[Element]'"

I'm obviously doing this all wrong.

My test code:

var elements = [[Element]]()

var body: some View {
    
    VStack {
        ForEach (0..<26) { index in
            Text("\(index) Hello, World!")
            
            elements.append(Element(direction: "Direction \(index)", movement: "Movement \(index)", multiplier: index))
        }
    }
  }
 }
  struct Element {
    var direction: String
    var movement: String
    var multiplier: Int
  }

1 Answer 1

3

You cannot perform any operation inside the ForEach. The ForEach expects to have a single View returned from it. But if you want to append data inside the ForEach then you can do that when the onAppear() closure is called on your View which is inside the ForEach.

This is what your code will look like when the elements array is appended in the onAppear of your View.

VStack {
        ForEach (0..<26) { index in
            Text("\(index) Hello, World!").onAppear() {
            
                elements.append(Element(direction: "Direction \(index)", movement: "Movement \(index)", multiplier: index))
            }
        }
    }

And you are getting the "immutable error" because you're probably declaring your elements variable inside the struct and properties inside the struct are immutable. So to be able to append new values you either need to annotate your elements variable with @State or you can declare it outside of the struct

Outside of struct declaration:

var elements: [Element] = []
struct MyView: View {
    
}

With annotation but inside struct declaration:

struct MyView: View {
    @State var elements: [Element] = []
}

And you also need to know that changing values of @State annotated properties updates the UI but this shouldn't be something to worry about as SwiftUI calculates the changes in the UI and updates only the new changes

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.