Van Du Tran
Van Du Tran

Reputation: 6892

Swift 2.2 #selector for delegate/protocol compile error

Here is my code:

protocol CustomControlDelegate: AnyObject {
    func buttonTapped(sender: AnyObject)
}

class CustomControl: UIView {
    var delegate: CustomControlDelegate? {
         didSet {
             aButton.addTarget(delegate, action: "buttonTapped:"), forControlEvents: UIControlEvents.TouchUpInside)
    }
}

As of Swift 2.2, I get a compile error asking to use #selector. But I can't figure out how to correctly use #selector in this case.

The compiler gave this suggestion:

enter image description here

but when that is used, it gave another compile warning saying:

enter image description here

I tried this and i did not get a compile error, however, I doubt it's the right solution. I don't want to add @objc to my protocol:

@objc protocol CustomControlDelegate: AnyObject {
    func buttonTapped(sender: AnyObject)
}

class CustomControl: UIView {
    var delegate: CustomControlDelegate? {
         didSet {
             aButton.addTarget(delegate, action: #selector(CustomControlDelegate.buttonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
    }
}

Upvotes: 2

Views: 862

Answers (1)

kennytm
kennytm

Reputation: 523344

I don't see the reason to avoid @objc here. The method must be @objc in order for the Objective-C runtime to invoke it. You can't put the @objc to the method declaration, so the only way to convey the intent is to make the protocol @objc.

@objc protocol CustomControlDelegate {
    func buttonTapped(sender: AnyObject)
}

Although the protocol is @objc, the implementing class does not need to be @objc — just making the method @objc can make the compiler happy.

class MyControlDelegate: CustomControlDelegate {
// ^ no `@objc`, not deriving NSObject
    @objc func buttonTapped(sender: AnyObject) {
    // ^ making just this method `@objc` is enough.

    }
}

then you could use #selector(CustomControlDelegate.buttonTapped) without errors or warnings.

Upvotes: 2

Related Questions