简体   繁体   中英

How to make a protocol extension constraint to two types in Swift

I have a protocol and its corresponding extension that looks something like this:

import Foundation


protocol HelpActionManageable {
    typealias ItemType : UIViewController,HelpViewControllerDelegate
    var viewController : ItemType {
        get
    }
}

extension HelpActionManageable  {
    func presentHelpViewController() {
        let helpViewController = HelpViewController(nibName: HelpViewController.nibName(), bundle: nil)
        viewController.presentViewController(helpViewController, animated: true, completion:nil)
        helpViewController.delegate = viewController
    }
    func dismissSuccessfulHelpViewController(helpViewController:HelpViewController) {
        helpViewController.dismissViewControllerAnimated(true) { () -> Void  in
            self.viewController.showAlertControllerWithTitle(GlobalConstants.Strings.SUCCESS, message: GlobalConstants.Strings.VALUABLE_FEEDBACK, actions: [], dismissingActionTitle: GlobalConstants.Strings.OK, dismissBlock: nil)
        }
    }
}

So, in a random view controller that confirms to this protocol, I am doing something like this:

class RandomViewController : UIViewController, HelpViewControllerDelegate,HelpActionManageable {
    //HelpViewControllerDelegate methods...
    var viewController : RandomViewController {
        return self
    }
}

This works fine, but it would be very neat if the extension HelpActionManageable methods are available for only types that confirm to UIViewController AND HelpViewControllerDelegate .

Something like this:

extension HelpActionManageable where Self == ItemType

This doesn't work. How can I achieve this in Swift?

I think this is supported now.

extension HelpActionManageable where Self == ItemType  {
}

or

extension HelpActionManageable where Self: ItemType  {
}

works for me.

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