How to cast controller to a specific protocol instead of a class in Swift?

250 Views Asked by At

This is my protocol:

protocol DBViewAnimationTransitioning {
    var viewForAnimation: UIView? { get set }
}

Example of usage inside prepareForSegue::

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let controller = segue.destinationViewController as? DBViewAnimationTransitioning {
        controller.viewForAnimation = sender as? UIView //cannot assign to to viewForAnimation in controller
    }
}

Everything is fine when I cast to specific controller f.e. DBFindViewController. But I need to cast this to the specific protocol not class. How to accomplish this?

2

There are 2 best solutions below

0
On BEST ANSWER

You can only check for protocol conformance (which includes is, as, and as?) with an @objc protocol.

So the solution is simple:

@objc protocol DBViewAnimationTransitioning {
    var viewForAnimation: UIView? { get set }
}

or:

protocol DBViewAnimationTransitioning: class {
    var viewForAnimation: UIView? { get set }
}
0
On

Because the protocol isn't specifically for a class/struct it cannot assign something because it may be a struct which would make no sense because it is copied. Try making it a class protocol by declaring it like protocol DBViewAnimationTransitioning : class