Binding is not acting like expected and I'd appreciate insights into what's going on.
Here's code that illustrates the issue. A class Model object called "Project" contains an array of Strings called "name". The code passes a Binding for name to a ViewModel of type ProjectVM for use in View. In the View's List I can delete a row, corresponding to deleting one of the elements of the String array, but then it comes right back.
This code should be operating on the original array since it's using a Binding, but apparently that's not what's happening. Any ideas?
It works as expected if the root object is an @State var of names (see commented-out code) instead of being a property of Project.
Using Xcode 12.4 with Swift 5
@main
struct Try_ArrayBindingApp: App {
@State var project = Project()
//@State var names = [ "a", "b", "c" ]
var body: some Scene {
WindowGroup {
ProjectV(pVM: ProjectVM(names: $project.names))
//ProjectV(pVM: ProjectVM(names: $names))
}
}
}
class Project { var names = [ "one", "two", "three"] }
class ProjectVM: ObservableObject {
@Binding var names: [String]
init(names: Binding<[String]> ) { self._names = names }
func delete(at offsets: IndexSet) {
names.remove(atOffsets: offsets)
}
}
struct ProjectV: View {
@ObservedObject var pVM: ProjectVM
var body: some View {
VStack {
List {
ForEach(pVM.names, id: \.self) { n in
Text(n)
}
.onDelete(perform: delete)
}
}
}
private func delete(at offsets: IndexSet) {
pVM.delete(at: offsets)
}
}