I have some class (class A: UIView
) that conforms protocol UIGestureRecognizerDelegate
from third-party library. I need to extend this class by adding some optional UIGestureRecognizerDelegate
method, for example gestureRecognizer:shouldRequireFailureOfGestureRecognizer:
. How to do that?
I have tried writing an extension for A
:
extension A {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
print("abcd") // BREAKPOINT NOT REACHABLE
}
}
Then an extension for a protocol (even without Self == A
):
extension UIGestureRecognizer where Self == A {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
print("abcd") // BREAKPOINT NOT REACHABLE
}
}
The only thing worked is subclassing A:
class B: A {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
print("abcd") // Hallelujah! BREAKPOINT IS reachable
}
}
But I have multiple views that have to be inherited from A
. And this leads to copy and paste one logic for each inherited class. I don’t want to repeat myself 🙂
2
Answers
After all efforts I found a satisfactory solution. So, in third-party library I had
And either
class B: A
andclass C: A
in that library. So I hane wroteThat's all. Minimum of code and self repeating.
If your based
A
class is a subclass ofNSObject
, you just need to conformA
to theUIGestureRecognizerDelegate
once:Now you can implement any of
UIGestureRecognizerDelegate
optional functions you like inside any extension of theA
you need.Also, you can extend the protocol itself with a constraint of
Self == A
(only ifA
already conforms toUIGestureRecognizerDelegate
) like: