1

Below is my code snippet?

extension UISwitch{
    open override func draw(_ rect: CGRect) {
        self.tintColor = UIColor.red
    }
}

As per apple documentation, you should not override in extension. I understand this. Now I am not getting an error in this code and all switches in my application are having red as tint color.

I have read articles that this is working because of dynamic dispatch as UISwitch is class in inherited by NSObject.

Can someone help me understand this concept? Why should we not do this? If swift is static dispatch how does this still work?

Tushar Limaye
  • 106
  • 2
  • 7
  • What's wrong with setting the `tintColor` property of the switch directly or in Interface Builder? – vadian Mar 20 '19 at 16:11
  • [This](https://stackoverflow.com/a/38270173/2062785) should pretty much answer your question. In short: Definitely should not and theoretically also cannot, but due to the interoperability with Objective-C, there's a compiler "gap" that allows you to override functions in extensions. – Mischa Mar 20 '19 at 16:27
  • Possible duplicate of [Overriding methods in Swift extensions](https://stackoverflow.com/questions/38213286/overriding-methods-in-swift-extensions) – Mischa Mar 20 '19 at 16:28

0 Answers0