Swift 2.2 #selector in protocol extension compiler error
ios, protocols, swift
Solution
I had a similar problem. here is what I did.
- Marked the protocol as @objc.
- Marked any methods I extended with a default behavior as optional.
Then used Self. in the #selector.
@objc public protocol UpdatableUserInterfaceType {
optional func startUpdateUITimer()
optional var updateInterval: NSTimeInterval { get }
func updateUI(notif: NSTimer)
}
public extension UpdatableUserInterfaceType where Self: ViewController {
var updateUITimer: NSTimer {
return NSTimer.scheduledTimerWithTimeInterval(updateInterval, target: self, selector: #selector(Self.updateUI(_:)), userInfo: nil, repeats: true)
}
func startUpdateUITimer() {
print(updateUITimer)
}
var updateInterval: NSTimeInterval {
return 60.0
}
}
Problem
I've got a protocol extension it used to work perfectly before swift 2.2. Now I have a warning that tells me to use the new `#selector`, but if I add it no method declared with Objective-C Selector. I tried to reproduce the issue in this few lines of code, that can be easily copy and paste also into playground ``` protocol Tappable { func addTapGestureRecognizer() func tapGestureDetected(gesture:UITapGestureRecognizer) } extension Tappable where Self: UIView { func addTapGestureRecognizer() { let gesture = UITapGestureRecognizer(target: self, action:#selector(Tappable.tapGestureDetected(_:))) addGestureRecognizer(gesture) } } class TapView: UIView, Tappable { func tapGestureDetected(gesture:UITapGestureRecognizer) { print("Tapped") } } ``` There is also a suggestion to append to that method in the protocol `@objc`, but if I do it asks me also to add it to the class that implements it, but once I add the class doesn't conform to the protocol anymore, because it doesn't seems to see the implementation in the protocol extension. How can I implement this correctly?