I have created a simple example of the problem I'm facing. I have two views, ListView and EditView. ListView is observing the UsersViewModel (plural) which contain a list of user names.
Using NavigationLink I want to present a form where I can edit the user name and this is where I'm getting confused. I have created a UserViewModel (singular) which I have the EditView observing, but when I try to call the EditView passing the value from the ForEach loop, I get a type mismatch error as I am not passing a UserViewModel.
Maybe I am misunderstanding the observable object. I thought I could change the user name on the edit form, navigate back to the list view and I would see the change in the list.
struct ListView: View {
// Observe the Users View Model
@ObservedObject var usersViewModel = UsersViewModel()
var body: some View {
NavigationView {
List() {
ForEach(usersViewModel.users) { user in
// FAILS with cannot converted "user" to expected type userViewModel
NavigationLink (destination: EditView(userViewModel: user)) {
Text("Hello \(user.name)")
}
}
}
.navigationBarTitle("User List", displayMode: .inline)
.onAppear(){
usersViewModel.loadUsers()
}
The edit view
struct EditView: View {
@ObservedObject var userViewModel: UserViewModel
var body: some View {
TextField("User Name", text: $userViewModel.user)