以下快速代码给出了Protocol 'DataSource' can only be used as a generic constraint because it has Self or associated type requirements
错误。怎么解决?
protocol DataSource {
associatedtype DataItem
func getItem(at index: Int) -> DataItem
}
struct DataSourceAgent: DataSource {
typealias DataItem = Int
func getItem(at index: Int) -> DataItem {
return 0
}
}
class SomeClass<T> {
private var dataSource: DataSource!
init(dataSource: DataSource) {
self.dataSource = dataSource
}
func getSomeStuff() -> T {
return dataSource.getItem(at: 0)
}
}
let sc = SomeClass<Int>(dataSource: DataSourceAgent())
答案 0 :(得分:1)
您不能以与使用普通协议相同的方式使用具有关联类型的协议,但是可以通过以下方式在DataSource
中将SomeClass
用作类型约束:
class SomeClass<T, D:DataSource> where D.DataItem == T {
private let dataSource:D
init(dataSource: D) {
self.dataSource = dataSource
}
func getSomeStuff() -> T {
return dataSource.getItem(at: 0)
}
}
let sc = SomeClass<Int, DataSourceAgent>(dataSource: DataSourceAgent())
print(sc.getSomeStuff())