I'm trying to implement a not trivial (at least for my level) relationship between types.
Class A and B are subclasses of a class MySuperClass, and I'm letting them implement a protocol "MyProtocol"
class MySuperclass {...}
protocol MyProtocol {
func myProtocolMethod()
}
class A:MySuperclass, MyProtocol {...}
class B:MySuperclass, MyProtocol {...}
My class "Container" has a variable x, which can be either an instance of A or B
class Container {... var x:???? ....}
As maybe imaginable from the ???? my problem is that I would like that I can use x as both as MyProtocol and MySuperclass.
Just today I solved a very similar problem in this thread and I thought I could apply that here but I'm not succeeding.
The idea would be to declare the type of the variable such that it satisfies a constraint <T where T:MySuperclass, T:MyProtocol>
, but where do I put that? Everything I have tried so far didn't really make sense and failed.
I tried, for example:
class Container<T where T:MySuperclass, T:MyProtocol>
class Container {... var x:T ...}
but I instantiate and assign T in Container
, and when I do this I get a compiler error:
class Container {... self.x = A() ....}
"Type A is not convertible to 'T'"
But actually it should, because A satisfies the type constraints.
Edit: Thanks to arshajii's anwer I understood why this is not possible. But I still need to know how to solve my initial problem.
I don't know if generics is actually the correct approach for this. I think I don't really need a type variable, what I need is rather something like an aggregate type...
Edit 2- I know I can implement this by just implementing a subclass. Was just wondering if there are other approaches. But thinking again a subclass seems to be the best way.
Thanks in advance.