我使用的是 Swift 2.2,我声明了一个具有关联类型的协议(protocol),如下所示:
protocol CollectionViewModeling {
associatedtype CellType
func cellAtIndexPath(indexPath: NSIndexPath) -> CellType
}
现在我有一个符合上述协议(protocol)的 View 模型协议(protocol):
enum MyItemCell {
case MyItemCell1, MyItemCell2
}
protocol ItemsListViewModeling: CollectionViewModeling {
associatedtype CellType = MyCell
}
最后,在其他地方,我想声明一个符合 le protocol ItemsListViewModeling 的 var:
var viewModel: ItemsListViewModeling
我收到这个错误:
Protocol 'ItemsListViewModeling' can only be used as a generic constraint because it has Self or associated type requirements
但是我可以很容易地创建一个实现这个协议(protocol)的类。
是否可以为关联的类型化协议(protocol)声明一个 var?当我在协议(protocol) ItemsListViewModeling 中给出关联类型的最终类型时,我不明白为什么我会从编译器中看到这个错误。
谢谢
最佳答案
You can't treat protocols with associated types like regular protocols and declare them as standalone variable types.
关于Swift 关联类型和协议(protocol)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36452303/