Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift calling subclass's overridden method from superclass

I was having an issue with a subclass's method getting called that overrode a method, so I created a small app to test it. When the superclass calls a method that its subclass overrides, the superclass's version of the method still gets called instead of the subclass's version, which overrides the superclass's method and should be the method getting called.

Expected output: sub foo

Actual output: super foo

Superclass:

class ViewController: UIViewController
{
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
    {
        foo()
    }

    func foo()
    {
        println("super foo")
    }
}

Subclass:

class SubclassViewController: ViewController
{
    override func foo()
    {
        println("sub foo")
    }
}
like image 580
Adam Evans Avatar asked Aug 29 '26 00:08

Adam Evans


1 Answers

Make sure that the object's class is SubclassViewController. Otherwise, it will not have any knowledge of the method which is overriden by subclass

like image 88
Andriy Gordiychuk Avatar answered Aug 31 '26 13:08

Andriy Gordiychuk