简体   繁体   English

符合协议的协议相关类型

[英]Protocol associated type that conforms to a protocol

Code

I have the following protocols: 我有以下协议:

protocol BaseViewController {
    typealias ViewModelType: BaseViewModel

    var viewModel: ViewModelType? { get set }
}

protocol BaseViewModel {
}

I also have the following protocol for a view model: 对于视图模型,我还具有以下协议:

protocol MainViewModel: BaseViewModel {
}

Then in my MainViewController: 然后在我的MainViewController中:

class MainViewController: UIViewController, BaseViewController {
    typealias ViewModelType = MainViewModel

    var viewModel: ViewModelType?

    ...
}

Errors 失误

On the MainViewController I get the error 在MainViewController上,我得到了错误

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

Below this are two related errors: 以下是两个相关的错误:

  1. On BaseViewController: 在BaseViewController上:

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

  1. In MainViewController on the viewModel property 在MainViewController的viewModel属性上

Inferred type 'BaseViewModel' (by matching requirement 'viewModel') is invalid: does not conform to 'BaseViewModel'

Desired Result 所需结果

I would like to restrict the value of ViewModelType to conform to protocol BaseViewModel. 我想限制ViewModelType的值以符合协议BaseViewModel。 If this can be accomplished another way, then that will answer my question. 如果这可以通过另一种方式完成,那将回答我的问题。 But I would like to know what I'm doing wrong here. 但是我想知道我在这里做错了什么。

我认为您需要协议BaseViewModel的具体实现,因此可以将MainViewModel定义为结构或类。

The documentation for typealias indicates it has the following format: typealias的文档指示其具有以下格式:

typealias-assignment → = type 类型别名分配→=类型

And type is defined as: 并且type定义为:

type → array-type dictionary-type function-type type-identifier tuple-type optional-type implicitly-unwrapped-optional-type protocol-composition-type metatype-type 类型→数组类型字典类型函数类型类型标识符元组类型可选类型隐式展开的可选类型协议组成类型元类型

And protocol-composition-type is defined as: protocol-composition-type定义为:

protocol-composition-type → protocol<protocol-identifier-listopt> 协议组成类型→协议<协议标识符列表选择>

So listing a protocol does not seem to be supported, so it's not clear why you're not getting a compilation error there. 因此,似乎不支持列出协议,因此不清楚为什么在此没有编译错误。 If you change it to that format, it seems to work (compiles but I have not tested you get the desired result): 如果将其更改为该格式,则似乎可以正常工作(编译,但我尚未测试您是否获得了预期的结果):

protocol BaseViewController {
    typealias ViewModelType = protocol<BaseViewModel>

    var viewModel: ViewModelType? { get set }
}

And: 和:

class ViewController: UIViewController, BaseViewController {
    typealias ViewModelType = protocol<MainViewModel>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM