swift - Cocoapod 中的可选协议(protocol)方法

标签 swift cocoapods protocols

我有几个协议(protocol)方法,开发人员在安装我的 cocoapod 时可以作为代理调用。然而,目前它们都需要实现。我该如何让它们成为可选的?这是其中的一个片段:

在我的 cocoapod 代码中:

public protocol ServiceDelegate: NSObjectProtocol {
    func didDetectDoubleTapGesture()
}

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

从开发者的角度来看:

extension ViewController: ServiceDelegate {

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

}

它目前有效,但我希望开发人员可以选择是否必须实现“didDetectDoubleTapGesture()”委托(delegate)方法。到目前为止,我已经尝试过“@objc”和“@Optional”。最干净的方法是什么?

最佳答案

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
}

关于swift - Cocoapod 中的可选协议(protocol)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54701804/

相关文章:

swift - 无法在 Swift 的数组中复制随机播放

ios - 从 XCAsset 目录获取数据

swift - 'NSInternalInconsistencyException',原因 : 'Only run on the main thread!' swift 4

ios - 我想将每个单元格链接到不同的 URL

swift - 为什么我的 pod 导入突然停止工作?

ftp - FTP双向数据连接双方能否发送数据

xcode6 - 如何使用框架、扩展和 CocoaPods 构建 Xcode 项目

ios - 可能有一个 CocoaPods 有一个包含主应用程序的搜索路径

linux - 动态修改数据流

ios - 与一名委托(delegate)和许多发件人的协议(protocol)?