Define a protocol to use as an option so that extensions are available or not:
protocol UIViewExtensions { }
then define the extension for the protocol, but only for subclasses of UIView (otherwise this will not work):
extension UIViewExtensions where Self: UIView { func testFunc() -> String { return String(tag) } }
The class defined for the protocol will also have the extension:
class A: UIView, UIViewExtensions { } A().testFunc()
And if it is not defined for the protocol, it will also not have an extension:
class B: UIView {} B().testFunc() //execution failed: MyPlayground.playground:17:1: error: value of type 'B' has no member 'testFunc'
UPDATE
Since protocol extensions do not fulfill class polymorphism , if you need to redefine functions, the only thing I can come up with is a subclass:
class UIViewWithExtensions: UIView { override func canBecomeFocused() -> Bool { return true } } UIViewWithExtensions().canBecomeFocused()
it can also be combined with an extension, but I donβt think it would make sense anyway.
Daniel
source share