This a proof of concept of an error I'm facing developing a SwiftUI application where I need data synced among views and that's the reason I'm using ObservedObject and Binding.
Here is the code of the application
import SwiftUI
struct Person: Hashable{
var id: String
var name: String
}
class People: ObservableObject{
@Published var items: [Person]
init (){
self.items = [
Person(id: "1", name: "Juan"),
Person(id: "2", name: "Javier"),
Person(id: "3", name: "Alvaro")
].sorted(by:{$0.name < $1.name})
}
}
struct ContentView: View {
@ObservedObject var people = People()
var body: some View {
NavigationView{
List{
ForEach(Array(people.items.enumerated()), id: \.1.id) { (index, _) in
NavigationLink(destination: PersonDetailView(person:Binding(
get: { self.people.items[index] },
set: { self.people.items[index] = $0 }))){
PersonListRowView(person: self.$people.items[index])
}
}
}
.navigationBarTitle("People", displayMode: .large)
.navigationBarItems(trailing:
Button(
action: {
self.people.items.removeLast()
},
label: { Image(systemName: "trash")
.frame(width: 30, height: 30)
}
)
)
}
}
}
struct PersonListRowView: View {
@Binding var person: Person
var body: some View {
Text("\(person.name)")
}
}
struct PersonDetailView: View {
@Binding var person: Person
var body: some View {
VStack{
Text("My name is \(self.person.name)")
Button("Change name"){
self.person.name = "Pepe"
}
}
}
}
The problem appears when I delete a Person in the list (clicking on the trash icon), I get an error and the app crashes.
After playing around a lot and reading many posts I see this problem is quite similar to Using ForEach loop with Binding causes index out of range when array shrinks (SwiftUI) but I use a NavigationLink and precisely that causes the problem. If you comment the NavigationLink, application runs smoothly when deleting an item
Any clue what is happening and how to fix it?