0

The code below throws an index out of range error when deleting TextField() but not when deleting Text().

Here is the full error: Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444

import SwiftUI

struct Information: Identifiable {
    let id: UUID
    var title: String
}

struct ContentView: View {

    @State var infoList = [
        Information(id: UUID(), title: "Word"),
        Information(id: UUID(), title: "Words"),
        Information(id: UUID(), title: "Wording"),
    ]


var body: some View {
    
    Form {
        ForEach(0..<infoList.count, id: \.self){ item in
            Section{
                
                
//                    Text(infoList[item].title) //<-- this doesn't throw error when deleted
                
                    TextField(infoList[item].title, text: $infoList[item].title)
            
            }
        }.onDelete(perform: deleteItem)
    }

}

    private func deleteItem(at indexSet: IndexSet) {
        self.infoList.remove(atOffsets: indexSet)
    }
}
Brenton Beltrami
  • 333
  • 6
  • 11
  • 1
    Does this answer your question https://stackoverflow.com/a/58911168/12299030? Also might be helpful https://stackoverflow.com/a/61435489/12299030. – Asperi Oct 06 '20 at 10:46
  • The first link seems to work but I am having trouble making it work with Identifiable. In particular getting the index to pass to EditorView. – Brenton Beltrami Oct 06 '20 at 11:09

1 Answers1

0

@Asperi's response about creating a dynamic container was correct. I just had to tweak a bit to make it compatible with Identifiable. Final code below:

import SwiftUI

struct Information: Identifiable {
let id: UUID
var title: String

}

struct ContentView: View {

@State var infoList = [
    Information(id: UUID(), title: "Word"),
    Information(id: UUID(), title: "Words"),
    Information(id: UUID(), title: "Wording"),
]




var body: some View {
    
    Form {
        ForEach(0..<infoList.count, id: \.self){ item in
            
            EditorView(container: self.$infoList, index: item, text: infoList[item].title)
                
            
        }.onDelete(perform: deleteItem)

      
    }

}

private func deleteItem(at indexSet: IndexSet) {
    
    
    
    self.infoList.remove(atOffsets: indexSet)
}
}


struct EditorView : View {
var container: Binding<[Information]>
var index: Int

@State var text: String

var body: some View {
    TextField("", text: self.$text, onCommit: {
        self.container.wrappedValue[self.index] = Information(id: UUID(), title: text)
    })
}
}
Brenton Beltrami
  • 333
  • 6
  • 11