I'm trying to generate a ForEach with a NavigationLink and use State and Binding to pass some entity around:
struct ContentView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(
entity: MyEntity.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \MyEntity.name, ascending: true)
]
) var entries: FetchedResults<MyEntity>
var body: some View {
NavigationView {
List {
ForEach(entries, id: \.self) { (entry: MyEntity) in
NavigationLink(destination: DetailView(myEntry: $entry)) {
Text(entry.name!)
}
}.
}
}
}
}
And then the following view:
struct DetailView: View {
@Binding var myEntry: MyEntity
var body: some View {
Text(myEntry.name!)
}
}
The problem is I can not pass the value to Detail view since the error:
Use of unresolved identifier '$entry'
What is wrong here and how to solve this?
If I just have a simple @State
its no problem to pass it via the binding, but I want/need to use it in the ForEach for the FetchedResults
EDIT: If I remove the $
I get Cannot convert value of type 'MyEntity' to expected argument type 'Binding<MyEntity>'
EDIT2: The purpose is to pass some object to DetailView and then pass it back later to ContentView
Use the following in ForEach
ForEach(entries, id: \.self) { entry in
NavigationLink(destination: DetailView(myEntry: entry)) {
Text(entry.name!)
}
}
and the following in DetailView
struct DetailView: View {
var myEntry: MyEntity
var body: some View {
Text(myEntry.name!)
}
}
The MyEntity
is class, so you pass object by reference and changing it in DetailView
you change same object.