【问题标题】:How to share an associatedtype between two protocols?如何在两个协议之间共享关联类型?
【发布时间】:2016-11-02 18:56:24
【问题描述】:

我需要声明两个协议,它们都有关联类型:

protocol MyView {
  associatedtype DataType
  associatedtype LayoutType : MyLayout

  var data: DataType { get }
  var layout: LayoutType { get }

  func doLayout()
}

protocol MyLayout {
  associatedtype DataType

  func computeLayout(with data: DataType?)
}

根据当前的协议定义,MyViewassociatedtype DataTypeMyLayout 中的并不完全相同:

extension MyView {
  func doLayout() {
    layout.computeLayout(with: self.data)
                               ^^^^^^^^^
    Cannot convert value of type 'Self.DataType' to expected argument type '_?'
  }
}

编译器告诉我们类型不一样。

有没有办法在两个协议之间共享关联类型来解决我的问题?谢谢。

【问题讨论】:

标签: ios swift associated-types


【解决方案1】:

问题是MyView 的实现可能有一个LayoutType 与它自己的DataType 不同的DataType。一旦SE-0142: Permit where clauses to constrain associated types 被实现,你就可以说:

associatedtype LayoutType : MyLayout where LayoutType.DataType == DataType

为了强制一致的类型必须有一个 LayoutType 和一个匹配的 DataType

但是,在这种情况发生之前,您可能能做的最好的事情就是将约束添加到扩展中——这只会在DataTypes 匹配时使doLayout() 的默认实现可用。

extension MyView where LayoutType.DataType == DataType {
    func doLayout() {
        layout.computeLayout(with: data)
    }
}

【讨论】:

    猜你喜欢
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 2011-04-20
    • 2020-11-14
    相关资源
    最近更新 更多