![](/img/trans.png)
[英]Inherit delegate methods from custom class and UIViewController (Objective C)
[英]Protocol requires that delegate inherit from UIViewController
我有一个协议ShareDelegate
,如下所示:
protocol ShareDelegate : class {
func share(event: EventJSONModel, skipToTime time: CMTime?, view: UIView, completion: @escaping () -> ())
}
extension ShareDelegate where Self: UIViewController {
func share(event: EventJSONModel, skipToTime time: CMTime? = nil, view: UIView, completion: @escaping () -> ()) {
}
}
然后,当我将其用作委托时:
weak var delegate: ShareDelegate?
然后调用委托函数:
delegate?.share(event: event, view: view, completion: completion)
它给了我以下错误
'ShareDelegate' requires that 'ShareDelegate' inherit from 'UIViewController'
如果我删除skipToTime time: CMTime?
部分扩展它工作正常。 为什么??
extension ShareDelegate where Self: UIViewController {
func share(...) {
}
}
由于上面的代码,你需要一个UIViewController
来使用扩展来确认委托,它看起来就像那样
extension UIViewController: ShareDelegate {
func share(...) {
}
}
问题是协议和默认实现之间的接口是不同的。
协议:
func share(event: EventJSONModel, skipToTime time: CMTime?, view: UIView, completion: @escaping () -> ())
延期:
func share(event: EventJSONModel, skipToTime time: CMTime? = nil, view: UIView, completion: @escaping () -> ())
所以你已经使用默认值声明skipToTime
在扩展中是可选的,所以当调用它并跳过该值时,你专门调用局限于UIViewController
的版本
更新:
您应该能够限制ShareDelegate协议的使用,以便它只适用于UIViewControllers,如下所示:
protocol ShareDelegate: class where Self: UIViewController {
func share()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.