3

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?

pkamb
  • 33,281
  • 23
  • 160
  • 191
Martin Massera
  • 1,718
  • 1
  • 21
  • 47
  • The body of a class and an extension can't both provide overrides. How would the compiler decide which to pick? – Alexander Apr 28 '17 at 18:37
  • well, maybe the extension could call `self.myMethod()` instead of `super.myMethod()` or something like that. Or that super for extensions meant the class ... whatever. Any ideas how to do that? – Martin Massera Apr 28 '17 at 18:41
  • You really need to read this: http://stackoverflow.com/questions/33862414/swift-override-function-in-extension or this: http://stackoverflow.com/questions/38213286/overriding-methods-in-swift-extensions – rmaddy Apr 28 '17 at 18:43
  • You should also provide the way in which you are going to reuse it... – iWheelBuy Apr 29 '17 at 13:10

1 Answers1

1

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

Answer is here Swift override function in extension

Martin Massera
  • 1,718
  • 1
  • 21
  • 47