Reputation: 3805
I have a quite specific problem and I wasn't able to solve this by the given answers on SO. To simplify this question, I removed everything that is not needed. This code just shows everything needed to understand the problem:
So I have a class that looks like this:
class DataSource<T> {
var data: [T] = []
}
Now I want a protocol, that inherits from that class but does not specify the generic (Is this even possible?)
Something like this: (This does not compile but this is the question)
protocol Example: DataSource<Item> {
associatedtype Item
func getItems() -> [Item]
}
It would be ok, to constrain the generic (e.g. with another protocol). Something like this:
protocol Example: DataSource<Item> where Item: Equatable { // or whatever
associatedtype Item
func getItems() -> [Item]
}
I tried in some different ways but none of my ideas worked. Is it possible to specify the generic from the associatedType of the protocol? Do I have to rethink this concept or am I just missing a little detail?
Upvotes: 4
Views: 1722
Reputation: 258541
Maybe you meant this:
class DataSource<T> {
var data: [T] = []
}
protocol Example {
associatedtype Item
func getItems() -> [Item]
}
extension DataSource: Example {
typealias Item = T
func getItems() -> [T] {
return self.data
}
}
Upvotes: 2