简体   繁体   中英

Protocol requires that delegate inherit from UIViewController

I have a protocol ShareDelegate that looks like this:

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

    }
}

Then when I use this as a delegate:

weak var delegate: ShareDelegate?

and then call the delegate function:

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

it gives me the following error

'ShareDelegate' requires that 'ShareDelegate' inherit from 'UIViewController'

If I remove the skipToTime time: CMTime? part of the extension it works fine. Why??

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

    }
}

Because of this code above, you need a UIViewController to confirm to the delegate using extension it would look something like that

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

    }
}

The issue is that the interface is different between the protocol and the default implementation.

protocol:

func share(event: EventJSONModel, skipToTime time: CMTime?, view: UIView, completion: @escaping () -> ())

Extension:

func share(event: EventJSONModel, skipToTime time: CMTime? = nil, view: UIView, completion: @escaping () -> ())

So you've declared skipToTime to be optional in the extension with a default value, so when calling it and skipping that value, you are specifically calling the version that is confined to UIViewController

UPDATE:

You should be able to restrict usage of your ShareDelegate protocol so that it only works with UIViewControllers like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM