【问题标题】:Swift associated types and protocol inheritanceSwift 关联类型和协议继承
【发布时间】:2016-04-06 13:14:44
【问题描述】:

我使用的是 Swift 2.2,并声明了一个关联类型如下的协议:

protocol CollectionViewModeling {
    associatedtype CellType
    func cellAtIndexPath(indexPath: NSIndexPath) -> CellType
}

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

enum MyItemCell {
    case MyItemCell1, MyItemCell2
}
protocol ItemsListViewModeling: CollectionViewModeling {
    associatedtype CellType = MyCell
}

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

var viewModel: ItemsListViewModeling

我收到了这个错误:

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

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

是否可以将 var 声明为关联的类型化协议?当我在协议 ItemsListViewModeling 中给出关联类型的最终类型时,我不明白为什么我会从编译器中看到此错误。

谢谢

【问题讨论】:

    标签: swift mvvm protocols associated-types


    【解决方案1】:

    见stackoverflow.com

    您不能将具有关联类型的协议视为常规协议 并将它们声明为独立变量类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多