我试图隐式定义关联类型,但出现错误:
'RowProtocol' is ambiguous for type lookup in this context
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)
我怎样才能做到这一点?
最佳答案
遵守 RowProtocol
需要将关联类型 T
映射到具体类型,而 Row
不会执行此操作。我假设您还想使 Row
通用,这就是为什么您没有从协议(protocol)中为 T
指定类型别名。
解决方案是使 Row
也通用:
struct Row<T>: RowProtocol {
let cellClass: T.Type
init(cellClass: T.Type) {
self.cellClass = cellClass
}
}
现在编译器很高兴,因为它有一个具体类型要传递给 RowProtocol
。请记住,对于编译器来说,Row
中的 T
与 RowProtocol
中的 T
不同,后者是协议(protocol)要求,而第一个是通用的。
// 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
}
}
关于ios - 未隐式定义关联类型的通用协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52086370/