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

时间:2018-12-12 14:30:07

标签: swift generics protocols

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

Snapshot of errors from playground

1 个答案:

答案 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())