Что я могу выяснить в этой ситуации, как показано ниже,
Вы должны создать 3 ViewModels
- ViewModel для
ViewController
- CustomTableViewCellViewModel для
CustomTableViewCellView
- CustomCollectionViewCellViewModel для
CustomCollectionViewCellView
А вот как ваш ViewModels
долженвыглядит,
class ViewModel
{
private var cellVMs = [CustomTableViewCellViewModel] = []
var reloadTableViewClosure: (()->())?
var numberOfLibraries: Int {
return self.cellVMs.count
}
func getLibraryCellVM(at indexPath: IndexPath) -> CustomTableViewCellViewModel
{
return self.cellVMs[indexPath.row]
}
//MARK: Initializer
init()
{
self.fetchLibraryList()
}
//MARK: Private Methods
private func fetchLibraryList()
{
if let path = Bundle.main.path(forResource: "LibraryList", ofType: "json")
{
if let libraryList = try? JSONDecoder().decode([Library].self, from: Data(contentsOf: URL(fileURLWithPath: path)))
{
libraryList.forEach({
cellVMs.append(CustomTableViewCellViewModel(library: $0))
})
self.reloadTableViewClosure?()
}
}
}
}
Ваш CustomTableViewCellViewModel
будет выглядеть следующим образом,
class CustomTableViewCellViewModel {
var booksVMs: [CustomCollectionViewCellViewModel] = []
var library: Library!
init(library: Library) {
self.library = library
// Initialize booksVMs
library.books.forEach({
booksVMs.append(CustomCollectionViewCellViewModel.init(book: $0))
})
}
var numberOfBooks: Int {
self.booksVMs.count
}
func bookViewModel(at indexPath: IndexPath) -> CustomCollectionViewCellViewModel {
return self.booksVMs[indexPath.row]
}
}
и, наконец, CustomCollectionViewCellViewModel
будет выглядеть следующим образом,
class CustomCollectionViewCellViewModel {
var book: Book!
init(book: Book) {
self.book = book
}
var bookName: String? {
return self.book.name
}
}