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)
    }
}
2

1 Answer 1

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)
    })
}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.