Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override a Swift method that has been overridden by an extension?

Tags:

swift

I'm trying to create an extension for debugging a class to print some output when you enter certain methods. I want to be able to reuse this code in many different classes, and I want to keep those classes clean from this debugging code while also not repeating code (keeping DRY). That's why I thought of using an extension like this:

class A: ... {
    override func myMethod() { 
        super.myMethod()
        print("hello A")
    }
}

extension A {
    override func myMethod() { 
        print("hello extension")
    }
}

And I would like that when myMethod() is called, to see this

hello extension
hello A

(or the other way around, I don't care)

But the problem is that the compiler is saying "myMethod() has already been overridden here"

Any ideas?

like image 244
Martin Massera Avatar asked Dec 04 '25 04:12

Martin Massera


1 Answers

Extensions can add new functionality to a type, but they cannot override existing functionality.

Answer is here Swift override function in extension

like image 187
Martin Massera Avatar answered Dec 05 '25 22:12

Martin Massera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!