协议要求委托从UIViewController继承

问题描述 投票:3回答:2

我有一个协议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?部分它工作正常。为什么??

ios swift
2个回答
1
投票

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

协议:

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()
}

1
投票
extension ShareDelegate where Self: UIViewController {
    func share(...) {

    }
}

由于上面的代码,你需要一个UIViewController来确认代理使用扩展名它看起来像那样

extension UIViewController: ShareDelegate {
    func share(...) {

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.