1

I'm trying to implement MVVM with swiftUI

So I have this view model

class HomeViewModel: ObservableObject {
    @Published var favoriteStores = Array<ItemStore>()

    init() {
        for i in 0...10 {
            favoriteStores.append(ItemStore(storeName: "Store \(i)", storeImg: "image url"))
        }
    }
}

And this view :

struct HomeView: View {
    @ObservedObject var homeVM = HomeViewModel()
    @State var faves = [
        ItemStore(storeName: "Store 0", storeImg: "image url"),
        ItemStore(storeName: "Store 1", storeImg: "image url"),
        ItemStore(storeName: "Store 2", storeImg: "image url")
    ]
    @State var searchText = ""


    var body: some View {
        NavigationView{
            GeometryReader { geometry in

                ScrollView{
                    VStack{

                        SearchBarView(searchText: self.$searchText)
                        Spacer()
                            .padding(.vertical, 5.0)
                        FavoriteStoresView(favoriteStores: self.homeVM.favoriteStores)
                        FiltersView()
                        StoresView()
                    }.padding()
                }

            }
        }
    }
}

the problem here is when i use self.homeVM.favoriteStores i got : '[ItemStore]' is not convertible to 'Binding<[ItemStore]>'

but when i use @State var faves instead , it works fine

i saw lot of tutorials , and it should work like that , because swiftUI handle this part , and it wrap it with Binding

Ouail Bellal
  • 1,554
  • 13
  • 27

1 Answers1

1

Change the line with FavoriteStoresView to:

FavoriteStoresView(favoriteStores: self.$homeVM.favoriteStores)

(add a $ before the member var)

Yonat
  • 4,382
  • 2
  • 28
  • 37