1
import SwiftUI

struct Item{
    var name = "My Item"
    var price = "10$"
}



struct ContentView: View {
    @State var items:[Item] = [Item(), Item()]

    var body: some View {
        VStack{
            ForEach(self.items.indices, id: \.self){index in
                HStack{
                    TextField("Item Name", text: self.$items[index].name)
                    TextField("Item Price", text: self.$items[index].price)
                }
            }
            
            HStack{
                Button(action: {self.addItem()}, label: {Text("Add Item")})
                Button(action: {self.removeItem()}, label: {Text("Remove Item")})
                
                Spacer()
            }
        }
            .padding()
    }
    
    func addItem(){
        self.items.append(Item())
    }
    
    func removeItem(){
        self.items.removeLast()
    }
}

In above example I created views in a loop using ForEach to be able to change values in struct and dynamically add and remove items. Adding items works, but removing item throws Fatal Error:

Fatal error: Index out of range: 
file /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.8.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift, line 444
2020-12-17 15:03:36.046851+0300 testapp[3205:76975]
Fatal error: Index out of range: 
file /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.8.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift, line 444

Error message in editor isn't very helpful:

AppDelegate.swift

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {    = | Thread 1: Fatal error: Index out of range

When I comment out TextFields removing items works fine. I suspect, that self.$items[index].name tries to get it's index, but it was removed.

Any help is appreciated.

Rocket Nikita
  • 470
  • 2
  • 7
  • 20

0 Answers0