title: SwiftUI: How to "swipe delete" an element in nested ForEach (grouped)
body: <p>I am trying to created a <strong>dynamic grouped List</strong> in SwiftUI and I wondering how to implement an <code>onDelete</code> in this case. From what I have read about <a href="https://developer.apple.com/documentation/swiftui/foreach/3364106-ondelete" rel="nofollow noreferrer">this method</a> it takes on an action that receives an <a href="https://developer.apple.com/documentation/foundation/indexset" rel="nofollow noreferrer">IndexSet</a>. That is all fine when you only have a single ForEach (no grouping) but when you add nested ForEach (implemented grouping) implementing "deleting with swipe" of items functionality breaks. The issue is that I am not sure if the <code>onDelete</code> should go on the outer <code>ForEach</code> or the inner one, both do not work as there is no way to detect from which <code>Category</code> object in <code>items</code> the passed <code>IndexSet</code> is so I can perform the removal of items. Any thoughts? Here is my model and view:</p>
  
  <p>model:</p>
  
  <pre class="lang-swift prettyprint-override"><code>class Product: Identifiable, ObservableObject {
      let id = UUID()
      var name: String
  
      init(name: String) {
          self.name = name
      }
  }
  
  class Category: Identifiable, ObservableObject {
      let id = UUID()
      @Published var products = [Product]()
      var categoryName = ""
  }
  
  class Categories: ObservableObject {
      @Published var items = [Category]()
  }
  </code></pre>
  
  <p>and view:</p>
  
  <pre class="lang-swift prettyprint-override"><code>struct ProductListView: View {
      @ObservedObject var categories: Categories = Categories()
  
  
      var body: some View {
              List {
                  ForEach(categories.items) { category in
                      Section(header: Text(category.categoryName)) {
                          ForEach(category.products) { product in
                              Text(product.name)
                          }
                          .onDelete(perform: self.removeItems)
                      }
                  }
              }
              .listStyle(GroupedListStyle())
      }
  
      func removeItems(at offsets: IndexSet) {
          // This does not work correctly with nested ForEach
  
          // How to correctly remove the swiped element from the `.products`
          // Not sure how to find the correct `Category` which element was swiped.
  
          offsets.forEach{ offset in
              print(offset) // prints 0, 1 etc.
          }
      }
  
  }
  </code></pre>