2016-02-14 88 views
0

代码符合一个协议协议相关联的类型

我有以下协议:

protocol BaseViewController { 
    typealias ViewModelType: BaseViewModel 

    var viewModel: ViewModelType? { get set } 
} 

protocol BaseViewModel { 
} 

我也有一个视图模型的以下协议:

protocol MainViewModel: BaseViewModel { 
} 

然后在我的MainViewController中:

class MainViewController: UIViewController, BaseViewController { 
    typealias ViewModelType = MainViewModel 

    var viewModel: ViewModelType? 

    ... 
} 

错误

在MainViewController我得到的错误

Type 'MainViewController' does not conform to protocol 'BaseViewController'

下面这两个相关的错误:

  1. 在BaseViewController:

Unable to infer associated type 'ViewModelType' for protocol 'BaseViewController'

  • 在MainViewController上视图模型属性
  • Inferred type 'BaseViewModel' (by matching requirement 'viewModel') is invalid: does not conform to 'BaseViewModel'

    所需的结果

    我想ViewModelType的值限制到符合协议BaseViewModel。如果这可以以另一种方式完成,那么这将回答我的问题。但我想知道我在这里做错了什么。

    回答

    0

    我认为你需要一个协议的具体实现BaseViewModel所以定义MainViewModel作为一个结构或类将工作。

    0

    为typealias文档指示它具有以下格式:

    typealias赋值→=类型

    type定义为:

    型→阵列类型字典型函数类型类型标识符 元组类型可选类型隐式解包可选类型 协议的组合物型元类型型

    protocol-composition-type定义为:

    协议的组合物型→协议<协议标识符listopt>

    所以列出了协议似乎不被支持,所以目前还不清楚为什么你没有收到编译错误。如果将其更改为该格式,似乎工作(编译但我没有测试你得到想要的结果):

    protocol BaseViewController { 
        typealias ViewModelType = protocol<BaseViewModel> 
    
        var viewModel: ViewModelType? { get set } 
    } 
    

    和:

    class ViewController: UIViewController, BaseViewController { 
        typealias ViewModelType = protocol<MainViewModel> 
    
    相关问题