Teetz
Teetz

Reputation: 3805

Protocol inheritance from a generic class using associatedType as Type

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

Answers (1)

Asperi
Asperi

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

Related Questions