Swift 关联类型和协议(protocol)继承

标签 swift mvvm protocols associated-types

我使用的是 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 中给出关联类型的最终类型时,我不明白为什么我会从编译器中看到这个错误。

谢谢

最佳答案

看那里stackoverflow.com

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/

相关文章:

arrays - 如何增加从数组中获取特定随机对象的可能性

ios - 在创建时向 UITableViewCell 添加偏移量?

ios - 线程 1 : Fatal error: Index out of range when index is less then array count

android - 膨胀 View 在 MVVM 设计模式中是如何工作的?

sql-server - ODBC、OLEDB 和 ADO.NET 的底层协议(protocol)有区别吗

ios - 使用 UITapGestureRecognizer 时的 EXC_BAD_ACCESS

mvvm - View 未在可绑定(bind)布局 xamarin 表单中刷新

c# - 根据MVVM模式-谁负责?

ssl - 在客户端和服务器(非 HTTPS)之间使用自定义协议(protocol)时是否需要 SSL 证书?

swift - UIView 和 UIViewController 之间的委托(delegate)/协议(protocol)不起作用