如何实现符合具有关联类型的协议的泛型 class?

How can I implement a generic class that conforms to a protocol with associated type?

以下 swift 代码给出了 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())

您不能像使用普通协议那样使用具有关联类型的协议,但您可以使用 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())