Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a subclass from its base class in swift

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".

like image 436
user3067870 Avatar asked Oct 10 '14 10:10

user3067870


People also ask

What is the difference between base class and subclass?

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).

What is Subclassing in Swift?

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.

What is overriding in Swift?

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.

Is a derived class a subclass?

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.


1 Answers

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()
like image 143
Martin R Avatar answered Sep 21 '22 01:09

Martin R