Andrea Mario Lufino Andrea Mario Lufino -4 years ago 67
iOS Question

Create protocol var that conforms to another protocol

I have my Swift project where I want to create an animator. I'll use this animator object in all my view controller creating a specific object for every one of them. The actual animator object must conform to the

protocol. See the example :

This is the
protocol :

protocol Animator {

associatedtype ViewControllerGeneric
var controller: ViewControllerGeneric { get }

/// Init the animator
/// - Parameter controller: The UIViewController to bind to the animator
init(withController controller: ViewControllerGeneric)

This is an actual animator object :

class SolutionAnimator: Animator {

private (set) var controller: SolutionsViewController

required init(withController controller: SolutionsViewController) {

self.controller = controller

Here everything is fine. Then, I want that all my
s subclasses adhere to my other protocol
, that is this :

protocol UIViewControllerAnimator {

associatedtype AnimatorObject: Animator
var animator: AnimatorObject { get set }

Here I want to have a var named
that is of a generic type
that have to conform to

When I write everything in MyViewController, like this :

class MyViewController: UIViewController, UIViewControllerAnimator {

var animator: SolutionAnimator!

Xcode tells me that
doesn't conform to protocol

Do you have any suggestion?

Answer Source

Your MyViewController doesn't conform to UIViewControllerAnimator. Your protocol requires:

associatedtype AnimatorObject: Animator
var animator: AnimatorObject { get set }

And your class provides:

var animator: SolutionAnimator!

But SolutionAnimator! doesn't conform to Animator. SolutionAnimator does. Remove the !.

If you have some technical reason that you cannot remove the ! (for instance, if this is being instantiated from a storyboard, that can be unworkable), then you just need to hide the ! so that you correctly conform to the protocol:

private var _animator: SolutionAnimator!
var animator: SolutionAnimator {
    get { return _animator }
    set { _animator = newValue }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download