I am trying to allow a method in a super class to return an instance of the subclass so that I can use method chaining with methods across both the parent and the child.
However, I am getting the error "BaseClass does not have a member named someOtherChainableMethod" when I attempt to chain the 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 issue seems to be that the 'return self' in the parent chain-able method is returning an instance with type BaseClass
rather than ChildClass
.
I have also tried this with generics and failed, this 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 from the BaseClass
someChainableMethod
method, is "BaseClass is not convertible to T".
Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).
Subclassing is the act of basing a new class on an existing class. The subclass inherits characteristics from the existing class, which you can then refine. You can also add new characteristics to the subclass.
This allows subclasses to directly access the superclass members. Now, if the same method is defined in both the superclass and the subclass, then the method of the subclass class overrides the method of the superclass. This is known as overriding.
The derived class (the class that is derived from another class) is called a subclass. The class from which its derived is called the superclass.
Your code works if you change the return type of the 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With