Protocol with generic class requirement

Hello everyone.

I am trying to build a framework that relies on generics heavily.
The problem I'm facing is that methods outputting opaque types can't be inherited, so I thought, well, I shall extract those requirements into protocols with associated types.

But here's another problem, the following code does not compile:

open class GenericClass<T1: Hashable, T2: Hashable> { }

public protocol GenericProtocol<T1, T2>: GenericClass<T1, T2> {   // ERROR: Cannot find type 'T1' in scope
  associatedtype T1: Hashable
  associatedtype T2: Hashable
}

So I think my approach is bad. Or is it not?
What next steps would you advice?

Thanks.

1 Like

While I don't think inheritance is a good idea, you can spell what you want using a where clause.

public protocol GenericProtocol<T1, T2> where Self: GenericClass<T1, T2> {
  associatedtype T1: Hashable
  associatedtype T2: Hashable
}

final class Object: GenericClass<Never, Never> & GenericProtocol {
  typealias T1 = Never
  typealias T2 = Never
}
2 Likes

Do you need the protocol at all? It seems like the base class alone is sufficient. Can you show a more complete example?

1 Like