Julien Fouilhé
Julien Fouilhé

Reputation: 2658

Function overload with subclass in swift

I have this code:

class A {

}

class B : A {

}

class Example {

    func action(_ param : A) -> String {
        return "A"
    }

    func action(_ param : B) -> String {
        return "B"
    }

    func test() -> String {
        let t : A = B()

        return self.action(t) // returns A
    }

}

I'm passing a B object but casted as A, therefore it calls action(_ param : A) when I want it to call the action(_ param : B) function.

Is it possible to do that without using is/as!?

Upvotes: 0

Views: 201

Answers (1)

matt
matt

Reputation: 535138

Polymorphism is exactly how you get rid of the if and is that you so dread. That, in fact, is what polymorphism is. The problem is that you use the word "polymorphic" but you forgot to use polymorphism. In effect, there is no polymorphism in your code. Polymorphism means that each class or subclass acts for itself. Thus:

class A {
    func who() -> String {return "A"}
}

class B : A {
    override func who() -> String {return "B"}
}

class Example {
    func action(_ param : A) -> String {
        return param.who()
    }
    func test() -> String {
        let t : A = B()
        return self.action(t) // returns B
    }
}

The alternative would be to say for example

return String(describing:type(of:param))

but I assume that you know that and that you count that as the same as saying is and as.

Upvotes: 4

Related Questions