ios - 协议(protocol)要求委托(delegate)继承自 UIViewController

标签 ios swift

我有一个看起来像这样的协议(protocol) 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 () -> ()) {

    }
}

然后当我将其用作委托(delegate)时:

weak var delegate: ShareDelegate?

然后调用委托(delegate)函数:

delegate?.share(event: event, view: view, completion: completion)

它给我以下错误

“ShareDelegate”要求“ShareDelegate”继承自“UIViewController”

如果我删除扩展的 skipToTime time: CMTime? 部分,它就可以正常工作。为什么??

最佳答案

问题是协议(protocol)和默认实现之间的接口(interface)不同。

协议(protocol):

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 协议(protocol)的使用,以便它仅适用于 UIViewControllers,如下所示:

protocol ShareDelegate: class where Self: UIViewController {
    func share()
}

关于ios - 协议(protocol)要求委托(delegate)继承自 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52402656/

相关文章:

swift - 我怎样才能动画这个 TableView 标题Y位置变化

swift 4 : getter and setter directly in a struct or class

javascript - 2D 游戏的最佳 HTML5/Javascript 引擎?

ios - swift playground/deinit{} 中的内存泄漏未被一致调用

ios - amazon s3client , awsios sdk 框架,在 iOS 7 中出现异常

ios - 撤销当前的 APNs key 会破坏实时应用程序吗?

ios - IOS Swift 中自动布局的对齐问题

ios - Swift 图片下载 TableView

iOS Facebook 插屏广告

iphone - cocos-2d :My app crashes when i close it via task manager