我在我的Swift项目中想要创建一个动画师。我将在所有视图控制器中使用此动画器对象,为其中每个对象创建一个特定的对象。实际的动画师对象必须符合Animator协议。参见示例:

这是Animator协议:

protocol Animator {

    associatedtype ViewControllerGeneric
    var controller: ViewControllerGeneric { get }

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

这是一个实际的动画师对象:
class SolutionAnimator: Animator {

    private (set) var controller: SolutionsViewController

    required init(withController controller: SolutionsViewController) {

        self.controller = controller
    }
}

这里一切都很好。然后,我希望所有UIViewController的子类都遵循我的其他协议UIViewControllerAnimator,即:
protocol UIViewControllerAnimator {

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

在这里,我想要一个名为animator的var,它是一种必须符合AnimatorObject协议的通用类型Animator

当我在MyViewController中编写所有内容时,如下所示:
class MyViewController: UIViewController, UIViewControllerAnimator {

    var animator: SolutionAnimator!
}

Xcode告诉我MyViewController不符合协议UIViewControllerAnimator

你有什么建议吗?

最佳答案

您的MyViewController不符合UIViewControllerAnimator。您的协议要求:

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

您的 class 提供:
var animator: SolutionAnimator!

但是SolutionAnimator!不符合AnimatorSolutionAnimator可以。删除!

如果您出于某种技术原因无法删除!(例如,如果从情节提要中实例化了!,则可能无法使用),那么您只需隐藏ojit_code,即可正确遵守协议:
private var _animator: SolutionAnimator!
var animator: SolutionAnimator {
    get { return _animator }
    set { _animator = newValue }
}

关于ios - 创建符合其他协议(protocol)的协议(protocol)var,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42514208/

10-12 14:42
查看更多