title: SwiftUI out of index when deleting an array element in ForEach
body: <p>I looked through different questions here, but unfortunately I couldn't find an answer. This is my code:</p>
  
  <p><strong>SceneDelegate.swift</strong></p>
  
  <pre><code>...
  let contentView = ContentView(elementHolder: ElementHolder(elements: ["abc", "cde", "efg"]))
  ...
  window.rootViewController = UIHostingController(rootView: contentView)
  </code></pre>
  
  <p><strong>ContentView.swift</strong></p>
  
  <pre><code>class ElementHolder: ObservableObject {
  
      @Published var elements: [String]
  
      init(elements: [String]) {
          self.elements = elements
      }
  }
  
  struct ContentView: View {
  
      @ObservedObject var elementHolder: ElementHolder
  
      var body: some View {
          VStack {
  
              ForEach(self.elementHolder.elements.indices, id: \.self) { index in
                  SecondView(elementHolder: self.elementHolder, index: index)
              }
  
          }
      }
  }
  
  struct SecondView: View {
  
      @ObservedObject var elementHolder: ElementHolder
      var index: Int
  
      var body: some View {
          HStack {
              TextField("...", text: self.$elementHolder.elements[self.index])
              Button(action: {
                  self.elementHolder.elements.remove(at: self.index)
              }) {
                  Text("delete")
              }
          }
      }
  
  }
  </code></pre>
  
  <p>When pressing on the delete button, the app is crashing with a Index out of bounds error.</p>
  
  <p>There are two strange things, the app is running when</p>
  
  <p>1) you remove the <code>VStack</code> and just put the <code>ForEach</code> into the <code>body</code> of the <code>ContentView.swift</code> or</p>
  
  <p>2) you put the code of the <code>SecondView</code> directly to the <code>ForEach</code></p>
  
  <p>Just one thing: I really need to have the <code>ObservableObject</code>, this code is just a simplification of another code.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I updated my code and changed <code>Text</code> to a <code>TextField</code>, because I cannot pass just a string, I need a connection in both directions.</p>