Subclass return from base class in swift

I am trying to allow a method in a superclass to return an instance of a subclass so that I can use a chain of methods with methods for both the parent and the child.

However, I get the error "BaseClass does not have a member named someOtherChainableMethod" when I try to bind methods. Here is my code:

class BaseClass { func someChainableMethod() -> BaseClass { return self } } class ChildClass: BaseClass { func someOtherChainableMethod() -> ChildClass { return self } } let childClass = ChildClass childClass.someChainableMethod().someOtherChainableMethoid() 

The problem is that the "return self" in the parent chain method returns an instance of type BaseClass , not ChildClass .

I also tried this with generics and could not, here is what I tried:

 class BaseClass<T> { func someChainableMethod() -> T { return self } } class ChildClass: BaseClass<ChildClass> { func someOtherChainableMethod() -> ChildClass { return self } } let childClass = ChildClass childClass.someChainableMethod().someOtherChainableMethoid() 

In this case, the error of the BaseClass someChainableMethod method is that "BaseClass does not convert to T".

+7
inheritance swift
source share
4 answers

Your code works if you change the return type of methods to Self :

 class BaseClass { func someChainableMethod() -> Self { return self } } class ChildClass: BaseClass { func someOtherChainableMethod() -> Self { return self } } let childClass = ChildClass() let foo = childClass.someChainableMethod().someOtherChainableMethod() 
+8
source share

Add someOtherChaingableMethod to the base class and leave the implementation empty.

0
source share

Since you already know that childClass is an instance of ChildClass, you can do

 (childClass.someChainableMethod() as ChildClass).someOtherChainableMethoid() 
0
source share

Just override the base class someChainableMethod

 class BaseClass { func someChainableMethod() -> Self{ return self } } class ChildClass: BaseClass { override func someChainableMethod() -> Self { return self } func A(){ } } var objChild = ChildClass() objChild.someChainableMethod() 
0
source share

All Articles