Swift覆盖泛型swift

时间:2018-01-24 09:57:44

标签: swift generics mvvm

我正在尝试为MVVM Swift实现泛型。我有两个基类,一个泛型类的协议。这里的特殊之处是继承。我尝试了三个小时,但我无法解决它:(。

protocol ObjectProtocol {
    var id: Int { get set }
    var name: String { get set }
}

class BaseViewModel<T: ObjectProtocol> {

    var objects: [T] = []

    init(){

    }
}

protocol ListViewControllerType {

    associatedtype T: ObjectProtocol
    associatedtype ViewModelType: BaseViewModel<T>
    var viewModel: ViewModelType! { get set }


    func showError(error: String)
}

extension ListViewControllerType  {

    func showError(error: String) {
        print(error)
    }
}

class Consult: ObjectProtocol {
    var id: Int = 1
    var name: String = "Consult"
}

class ConsultViewModel<T: Consult>: BaseViewModel<Consult> {

}

class ConsultViewController: ListViewControllerType {
    var viewModel: ConsultViewModel<Consult>!
}

但我在var viewModel: ConsultViewModel<Consult>!

中收到错误

这是错误:Type 'ConsultViewController' does not conform to protocol 'ListViewControllerType'

有人有通用和继承的经验可以帮助我。 非常感谢你。

1 个答案:

答案 0 :(得分:0)

我通常会这样:

class BaseViewModel {
}

class TemplateViewModel<T: ObjectProtocol>: BaseViewModel {
    var objects: [T] = []
    init(){
    }
}