0

I have several protocol methods that a develop can call as delegates when they install my cocoapod. However, they are currently all required to be implemented. How do I go about making them optional? Here's a snippet of one:

In my cocoapod's code:

public protocol ServiceDelegate: NSObjectProtocol {
    func didDetectDoubleTapGesture()
}

//To fire the protocol method...
delegate?.didDetectDoubleTapGesture()

From the developer's side:

extension ViewController: ServiceDelegate {

    func didDetectDoubleTapGesture() {
        print("didDetectDoubleTapGesture")
    }

}

It currently works, but I want to make it optional for the developer to have to implement the 'didDetectDoubleTapGesture()' delegate method. So far I have tried '@objc' and '@optional'. What is the cleanest way to do this?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Caleb Rudnicki
  • 345
  • 8
  • 17
  • `@optional` means optional. What isn't "clean" about it? – matt Feb 15 '19 at 03:52
  • 1
    Possible duplicate of [How to define optional methods in Swift protocol?](https://stackoverflow.com/questions/24032754/how-to-define-optional-methods-in-swift-protocol) – Gustavo Conde Feb 15 '19 at 04:02

1 Answers1

0
If you want to use optional methods, you must mark your protocol with @objc attribute:

@objc protocol ServiceDelegate: NSObjectProtocol {
   @objc optional func didDetectDoubleTapGesture()
}

//To fire the protocol method...
delegate?.didDetectDoubleTapGesture()

extension ViewController: ServiceDelegate {

//no error
}

************************** or **********************
public protocol ServiceDelegate: NSObjectProtocol {
    func didDetectDoubleTapGesture()
}

//To fire the protocol method...
delegate?.didDetectDoubleTapGesture()

extension ServiceDelegate {
    func didDetectDoubleTapGesture()
}

extension ViewController: ServiceDelegate {

//no error
}