Cannot convert value of type 'AnyViewModel<BookListState, Never>.Type' to expected argument type 'AnyViewModel<BookListState, Never>'

I want to put BookListView() on the content view but it throw error like "Cannot convert value of type 'AnyViewModel<BookListState, Never>.Type' to expected argument type 'AnyViewModel<BookListState, Never>'" Any idea?

BookListView:


import SwiftUI

struct BookListState {
  var service: BookService
  var books: [Book]
}

struct BookListView: View {

  @ObservedObject var viewModel: AnyViewModel<BookListState, Never>

  var body: some View {
    NavigationView {
      ScrollView {
      VStack(alignment: .leading){
      ForEach(viewModel.state.books) { book in
        NavigationLink(destination: NavigationLazyView(BookDetailView(service: self.viewModel.state.service, bookId: book.id))) {
          BookRow(book: book)
        }
      }
     
      }
      }
    }
  }
}

struct BookListView_Previews: PreviewProvider {
  static var previews: some View {
    let viewModel = AnyViewModel(BookListViewModel(service: MockBookService()))
    return BookListView(viewModel: viewModel)
  }
}

ContentView:

import SwiftUI

struct ContentView: View {
  var body: some View {
   BookListView(viewModel: viewModel)
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}
Answered by Claude31 in 690636022

viewModel is not defined for ContentView (at least with the code you showed). Where did you declare it ?

You could declare it locally (as seen in tutorial you used):

  var body: some View {
        let viewModel = AnyViewModel(BookListViewModel(service: bookService))
        BookListView(viewModel: viewModel)
  }
Accepted Answer

viewModel is not defined for ContentView (at least with the code you showed). Where did you declare it ?

You could declare it locally (as seen in tutorial you used):

  var body: some View {
        let viewModel = AnyViewModel(BookListViewModel(service: bookService))
        BookListView(viewModel: viewModel)
  }
Cannot convert value of type 'AnyViewModel&lt;BookListState, Never&gt;.Type' to expected argument type 'AnyViewModel&lt;BookListState, Never&gt;'
 
 
Q