I'm trying to add some base-classes to an iOS app using MVVM, to make it easier and enforce a common class relationship.
Sadly, I'm running into the following issue:
error: MyPlayground.playground:27:7: error: type 'ListView' does not
conform to protocol 'MVVMView'
class ListView: MVVMView {
I'm not sure why this happens and kind of breaks my idea of "forcing" my code into this architecture. Is there something obvious I'm missing? Is there a workaround for me to fix this and keep the "enforced" architecture?
Note: I'm running on swift 5.
/**
Base classes for MVVM
*/
protocol MVVMViewModel {
}
protocol MVVMView {
associatedtype ViewModel: MVVMViewModel
var viewModel: ViewModel { get }
}
/**
Simple viewmodel, only used by protocol so it can be replaced when testing
*/
protocol ListViewModelProtocol: MVVMViewModel {
}
class ListViewModel: ListViewModelProtocol {
}
/*
Simple view
*/
class ListView: MVVMView {
typealias ViewModel = ListViewModelProtocol
var viewModel: ListViewModelProtocol
init(viewModel: ListViewModelProtocol) {
self.viewModel = viewModel
}
}
This is a tricky case. The solution is to replace
associatedtype ViewModel: MVVMViewModel
with
associatedtype ViewModel = MVVMViewModel
Why?
You described MVVMView as something that has a viewModel propery with type that conforms to MVVMViewModel. You can try to create a class like this
class AnyView: MVVMView { typealias ViewModel = MVVMViewModel var viewModel: MVVMViewModel
init(viewModel: MVVMViewModel) { self.viewModel = viewModel }
}
You'll have the error, saying MVVMViewModel does not conform to MVVMViewModel So MVVMViewModel does not conform to itself as any protocol in swift
You can find more detailed explanation, here I have found one Protocol doesn't conform to itself?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.