I'm trying to learn SwiftUI, and how bindings work.
I have this code that works, that shows a list of projects. When one project is tapped, a binding to that project is passed to the child view:
struct ProjectsView: View {
@ObjectBinding var state: AppState
@State var projectName: String = ""
var body: some View {
NavigationView {
List {
ForEach(0..<state.projects.count) { index in
NavigationLink(destination: ProjectView(project: self.$state.projects[index])) {
Text(self.state.projects[index].title)
}
}
}
.navigationBarTitle("Projects")
}
}
}
The child view, where I'm mutating the project using a binding:
struct ProjectView: View {
@Binding var project: Project
@State var projectName: String = ""
var body: some View {
VStack {
Text(project.title)
TextField(
$projectName,
placeholder: Text("Change project name"),
onCommit: {
self.project.title = self.projectName
self.projectName = ""
})
.padding()
}
}
}
However, I would rather iterate over the projects array without using indexes (beacuse I want to learn, and its easier to read), but not sure how I then can pass the binding to a single project. I tried it like this, but then I can't get access to project.title, since it's a binding, and not a String.
ForEach($state.projects) { project in
NavigationLink(destination: ProjectView(project: project)) {
Text(project.title)
}
}
How can I achieve this?

CurrentValueSubjectpassed to the Child instead ofBindingbut maybe it is overly complicated...ProjectisIdentifiable, yes.