Krisztian
Krisztian

Reputation: 477

Swift - Return subclass type in overridden function of superclass

I am trying to implement a Chainable object design in swift. This is my structure:

class A{
    func get() -> some A{
        return self
    }
}

class B:A{
    func set(){

    }
}

Can I create a method that would work even if I create a subclass of the original class? In my example, if I call get on B I will get an object of type A that does not have a method named set.

let b = B()
b.get().set() // A has no member 'set'

So for this to work I would have to manually override every function in from A in B which is not the worst since I can call super but still wasting time and duplication of code.

Upvotes: 0

Views: 522

Answers (1)

Marco Boschi
Marco Boschi

Reputation: 2333

If you don't really need to use an opaque type with the some keyword, you can obtain what you want using protocols and extensions:

protocol Chainable { 
    func get() -> Self 
} 
extension Chainable { 
    func get() -> Self { 
        return self 
    } 
} 
class A: Chainable {}
class B: A { 
    func set() { 
        print("ok") 
    } 
} 

Now you get the desired return type for your get function:

let a = A()
a.get() // Type = A
let b = B()
b.get() // Type = B
b.get().set() // Prints 'ok'

If you don't need to reuse this across multiple class hierarchies the solution can be even simpler (thanks to @Joakim Danielson for pointing this out):

class A {
    func get() -> Self { 
        return self 
    }
}
class B: A {  
    func set() {  
        print("ok")  
    }  
} 

Upvotes: 6

Related Questions