Check if an object is a specific class and conforms to a protocol

Viewed 962

Not sure if this is a weird way to do this but in Swift 3 I want to check if an object is a UIViewController and conforms to my protocol Transitionable. I have:

guard let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to),
    let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
    let toTransitionable = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? Transitionable,
    let fromTransitionable = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? Transitionable
else {
    transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
    return
}

But i was hoping I could get and object that is both UIViewController and Transitionable for the to and from. i tried let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? Transitionable as? UIViewController but that keeps it as just a UIViewController

I also tried:

extension Transitionable where Self: UIViewController {
    var viewController: UIViewController { return self }
}

But i get the error: 'Transitionable' is not a subtype of 'UIViewController' when i call toTransitionable.viewController e.g.

transitionContext.containerView.addSubview(toTransitionable.viewController.view)

I understand we can do as? (UIViewController & Transitionable) in Swift 4 but this project is going to be in Swift 3

1 Answers
Related