简体   繁体   English

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

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

Following swift code gives the Protocol 'DataSource' can only be used as a generic constraint because it has Self or associated type requirements error. 以下快速代码给出了Protocol 'DataSource' can only be used as a generic constraint because it has Self or associated type requirements错误, Protocol 'DataSource' can only be used as a generic constraint because it has Self or associated type requirements How can it be fixed? 如何解决?

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

操场上的错误快照

You can't use a protocol with associated type the same way as you would use normal protocol, but you can use DataSource as type constraint in SomeClass in this way: 您不能以与使用普通协议相同的方式使用具有关联类型的协议,但是可以通过以下方式将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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM