【问题标题】:Generic Protocol with Associated Type Not Defining Implicitly具有未隐式定义的关联类型的通用协议
【发布时间】:2018-08-29 21:33:44
【问题描述】:
我正在尝试隐式定义关联类型,但出现错误:
'RowProtocol' 在这种情况下对于类型查找是不明确的
protocol RowProtocol {
associatedtype T
var cellClass: T.Type { get }
init(cellClass: T.Type)
}
struct Row: RowProtocol {
let cellClass: T.Type
init(cellClass: T.Type) {
self.cellClass = cellClass
}
}
然后您可以使用以下方法对其进行初始化:
let implicitRow = Row(cellClass: Cell.self)
我怎样才能做到这一点?
【问题讨论】:
标签:
ios
swift
generics
protocols
associated-types
【解决方案1】:
符合RowProtocol 要求将关联类型T 映射到具体类型,而Row 不这样做。我假设您还想将Row 设为通用,这就是您没有从协议中为T 指定类型别名的原因。
解决方案是将Row 也设为通用:
struct Row<T>: RowProtocol {
let cellClass: T.Type
init(cellClass: T.Type) {
self.cellClass = cellClass
}
}
现在编译器很高兴,因为它有一个具体的类型可以传递给RowProtocol。请记住,尽管对于编译器而言,Row 中的 T 与 RowProtocol 中的 T 不同,后者是协议要求,而第一个是通用要求。
// exactly the same struct, but with different name for the generic argument.
struct Row<U>: RowProtocol {
let cellClass: U.Type
init(cellClass: U.Type) {
self.cellClass = cellClass
}
}