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

Animator
protocol. See the example :

This is the
Animator
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
UIViewController
s subclasses adhere to my other protocol
UIViewControllerAnimator
, that is this :

protocol UIViewControllerAnimator {

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


Here I want to have a var named
animator
that is of a generic type
AnimatorObject
that have to conform to
Animator
protocol.

When I write everything in MyViewController, like this :

class MyViewController: UIViewController, UIViewControllerAnimator {

var animator: SolutionAnimator!
}


Xcode tells me that
MyViewController
doesn't conform to protocol
UIViewControllerAnimator
.

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