简体   繁体   English

仅在符合 Class AND 协议时才进行 Swift 扩展

[英]Swift extension only when conforming to Class AND protocol

I have two protocols with extensions LoginPresenting and LoginDismissing .我有两个扩展名为LoginPresentingLoginDismissing协议。 I want LoginPresenting extension only to apply to UIViewControllers that also implement LoginDismissing .我希望LoginPresenting扩展仅适用于也实现LoginDismissing UIViewControllers I am trying to do it like so but have so far been unable to work out the syntax.我正在尝试这样做,但到目前为止还无法计算出语法。

protocol LoginDismissing : class {
    func loginHasCompleted(withController: UIViewController)
}

extension LoginDismissing where Self:UIViewController {
    func loginHasCompleted(withController controller:UIViewController) {
        //...code ommited
    }
}

protocol LoginPresenting : class {
    func presentLogin()
}

The following is bad code , but I think it explains how I am attempting to make LoginPresenting only apply to UIViewControllers that also implement LoginDismissing.以下是错误代码,但我认为它解释了我如何尝试使 LoginPresenting 仅适用于也实现 LoginDismissing 的 UIViewControllers。

extension LoginPresenting where Self:UIViewController, LoginDismissing //Syntax error here

    func presentLogin() {
        let lc = LoginViewController()
        let nav = UINavigationController(rootViewController: lc)
        nav.modalPresentationStyle = .fullScreen
        lc.loginDismissingDelegate = self //type LoginDismissing
        self.present(nav, animated: true, completion: nil)
    }
}

You can resolve your syntax error with the use of & instead of a comma:您可以使用&而不是逗号来解决语法错误:

extension LoginPresenting where Self: UIViewController & LoginDismissing {
    // ...
}

This makes the extension only apply to view controllers that also conform to LoginDismissing .这使得扩展仅适用于也符合LoginDismissing视图控制器。

You should enforce as many requirements as possible on the protocol itself, not the extensions.您应该对协议本身而不是扩展强制执行尽可能多的要求。

protocol LoginPresenting: LoginDismissing & UIViewController {
  func presentLogin()
}

Also, class is old syntax, though not deprecated.此外, class是旧语法,但不推荐使用。

protocol LoginDismissing: AnyObject {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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