我有几个协议(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/