title: SwiftUI ForEach over @State dynamic array
body: <p>There are a lot of similar questions on SO that I have found and tried to implement. None of them work properly for a dynamic array in the way I'm using it, so I don't think this is a duplicate. I tried a lot of solutions from others. The best I can find is <a href="https://stackoverflow.com/questions/57340575/binding-and-foreach-in-swiftui">this one</a>. But none of these work for dynamic arrays and <code>ForEach</code>.</p>
  <p>How do I loop over an <code>@State</code> struct's array and bind to those values?</p>
  <p>I have the following example code:</p>
  <pre><code>struct Items {
      var items: [Item] = [Item(text: &quot;test1&quot;), Item(text: &quot;test2&quot;), Item(text: &quot;test3&quot;)]
  
      // Lots of functions to work with items in my program
  }
  
  struct Item: Identifiable {
      let id = UUID()
      var text: String
      // Lots of other properties on an item
  }
  
  struct WindsView: View {    
      @State private var myItems = Items()
  
      var body: some View {
          NavigationView {
              Form {
                  Section(header: Text(&quot;Test&quot;)) {
  
                      // This does not work of course, as item is not a Binding
                      ForEach(myItems.items) { item in
                          NumberTextField&lt;Int&gt;(&quot;Item Text&quot;, number: item, isDecimalAllowed: false)
                      }
                  }
  
                  Section(header: Text(&quot;Test2&quot;)) {
  
                      // This is what most solutions come up with. However, my `MyItems`
                      // can have elements removed. If you run the code and click the button
                      // below, you will see that it breaks with an index out of range.
                      ForEach(myItems.items.indices) { i in
                           TextField(&quot;Item Text&quot;, text: $myItems.items[i].text)
                      }
                  }
  
                  Button(&quot;Break Me&quot;) { myItems.items.popLast() }
  
              }.navigationTitle(&quot;Help Me&quot;)
          }
      }
  }
  </code></pre>
  <p>I understand why it doesn't work without passing in a binding, and why it crashes when I use indices. So I'm trying to figure out how to do this right.</p>
  <p>Screenshots (With the code that clearly doesn't work commented out) before pushing the button:</p>
  <p><a href="https://i.stack.imgur.com/hJanL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hJanL.png" alt="enter image description here" /></a></p>
  <p>And after pushing it</p>
  <p><a href="https://i.stack.imgur.com/Kfn5X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kfn5X.png" alt="enter image description here" /></a></p>