【问题标题】:Optional Protocol Method in a CocoapodCocoapod 中的可选协议方法
【发布时间】:2019-07-09 03:40:08
【问题描述】:

我有几个协议方法,开发人员在安装我的 cocoapod 时可以作为委托调用这些方法。但是,它们目前都需要实施。我该如何让它们成为可选的?这是一个的sn-p:

在我的 cocoapod 的代码中:

public protocol ServiceDelegate: NSObjectProtocol {
    func didDetectDoubleTapGesture()
}

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

从开发者的角度来看:

extension ViewController: ServiceDelegate {

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

}

它目前可以工作,但我想让开发人员选择它来实现“didDetectDoubleTapGesture()”委托方法。到目前为止,我已经尝试过“@objc”和“@optional”。最干净的方法是什么?

【问题讨论】:

标签: swift cocoapods protocols


【解决方案1】:
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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多