Martin Massera
Martin Massera

Reputation: 1906

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

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?

Upvotes: 3

Views: 959

Answers (1)

Martin Massera
Martin Massera

Reputation: 1906

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

Answer is here Swift override function in extension

Upvotes: 1

Related Questions