The problem is that Objective-C knows nothing of protocol extensions. Thus, you cannot use a protocol extension to inject a method into a class in such a way that Objective-C's messaging mechanism can see it. You need to declare bar
in the view controller class itself.
(I realize that this is precisely what you were trying to avoid doing, but I can't help that.)
A sort of workaround might be this:
override func viewDidLoad() {
super.viewDidLoad()
foo = "testing"
let tapGesture = UITapGestureRecognizer(target: self, action: "baz")
self.view.addGestureRecognizer(tapGesture)
}
func baz() {
self.bar()
}
We are now using Objective-C's messaging mechanism to call baz
and then Swift's messaging mechanism to call bar
, and of course that works. I realize it isn't as clean as what you had in mind, but at least now the implementation of bar
can live in the protocol extension.
(Of course, another solution would be to do what we did before protocol extensions existed: make all your view controllers inherit from some common custom UIViewController subclass containing bar
.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…