小编Ant*_*nin的帖子

Swift关联类型和协议继承

我正在使用Swift 2.2并且我声明了一个具有相关类型的协议如下:

protocol CollectionViewModeling {
    associatedtype CellType
    func cellAtIndexPath(indexPath: NSIndexPath) -> CellType
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个符合上述协议的视图模型协议:

enum MyItemCell {
    case MyItemCell1, MyItemCell2
}
protocol ItemsListViewModeling: CollectionViewModeling {
    associatedtype CellType = MyCell
}
Run Code Online (Sandbox Code Playgroud)

最后,在其他地方,我想声明一个符合le协议ItemsListViewModeling的var:

var viewModel: ItemsListViewModeling
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

协议'ItemsListViewModeling'只能用作通用约束,因为它具有Self或关联类型要求

但我可以轻松创建一个实现此协议的类.

是否可以将var声明为关联的类型协议?因为我在协议ItemsListViewModeling中给出了相关类型的最终类型,所以我不明白为什么我从编译器中看到这个错误.

谢谢

protocols mvvm associated-types swift

7
推荐指数
1
解决办法
1692
查看次数

标签 统计

associated-types ×1

mvvm ×1

protocols ×1

swift ×1