0

With the code below I have one row in the second section of a form. When the onDelete executes, I can see (via breakpoints) that it successfully removes the record from the array. The body gets refreshed as it's a state variable and then it crashes with a Fatal error: Index out of range: file. The crash occurs when it tries to do the ForEach again which at this point should show nothing since the array is empty.

struct BuyerCheckout: View {
    @State private var subTotal:Double!
    @State private var tax:Double!
    
    @State private var fees = [FeeModel(type: "", amount: 0.00)]
    
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Gross Amounts")) {
                    HStack {
                        Text("Subtotal: $")
                        TextField("Purchase Subtotal", value: $subTotal, formatter: NumberFormatter.currency)
                            .keyboardType(.decimalPad)
                    }
                    HStack {
                        Text("Tax: $")
                        TextField("Purchase Tax", value: $tax, formatter: NumberFormatter.currency)
                            .keyboardType(.decimalPad)
                    }
                }
                
                Section(header: Text("Other Fees")) {
                    ForEach(fees.indices, id: \.self) {
                        FeeCell(fee: self.$fees[$0])
                    }
                    .onDelete(perform: removeRows)
                }
            }.gesture(DragGesture().onChanged { _ in
                UIApplication.shared.windows.forEach { $0.endEditing(false) }
            })
            .padding()
            .navigationBarTitle("Checkout")
            .onAppear {
                UITableViewCell.appearance().selectionStyle = .none
            }
        }
}

I am also doing the ForEach with indexes this way as the variable represents a binding for the FeeCell. I cannot pass a binding with the ForEach iterator of the array. Not sure this is relevant, but I thought I'd mention.

C6Silver
  • 3,127
  • 2
  • 21
  • 49
  • 2
    Does this answer your question https://stackoverflow.com/a/61706902/12299030? – Asperi Sep 13 '20 at 04:10
  • @Asperi - Thanks very much and yes it does. At the same time, that is quite the hoop to jump through for what at first glance seems a common need. Either my process is not the way this kind of need should be solved or SwiftUI needs some serious correction in this area. Thanks again! – C6Silver Sep 13 '20 at 05:41

0 Answers0