I've seen several posts about this, but so far none of the solutions seem to be working for me.
I'm trying to create an array of Identifiable items using ForEach -- with both a Text()
and Toggle()
view inside. The array is stored in a @Published
property of an @ObservableObject
.
I'm currently looping through the indices to create the toggle bindings (as suggested in other posts).
Everything appears to be working, until I try to delete a row.
(Specifically the last row - which triggers a "Fatal error: Index out of range" every time.)
Any help would be greatly appreciated!
struct Rule: Identifiable {
let id: String
var displayName: String
var isEnabled: Bool
}
class UserData: ObservableObject {
@Published var rules: [Rule] = []
}
struct RuleListView: View {
@ObservableObject var userData: UserData
var body: some View {
List {
ForEach(userData.rules.indices, id: \.self) { index in
HStack {
Toggle(
isOn: self.$userData.rules[index].isEnabled
) { Text("Enabled") }
Text(self.userData.rules[index].displayName)
}
}
.onDelete(perform: delete)
}
}
func delete(at offsets: IndexSet) {
userData.rules.remove(atOffsets: offsets)
}
}