【问题标题】:Create protocol var that conforms to another protocol创建符合另一个协议的协议变量
【发布时间】:2023-03-18 14:22:01
【问题描述】:

我有一个 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
    }
}

这里一切都很好。然后,我希望我的所有UIViewControllers 子类都遵守我的其他协议UIViewControllerAnimator,就是这样:

protocol UIViewControllerAnimator {

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

这里我想要一个名为animator 的变量,它是一个泛型类型AnimatorObject,它必须符合Animator 协议。

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

class MyViewController: UIViewController, UIViewControllerAnimator {

    var animator: SolutionAnimator!
}

Xcode 告诉我MyViewController 不符合协议UIViewControllerAnimator

你有什么建议吗?

【问题讨论】:

    标签: ios swift animation protocols


    【解决方案1】:

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

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

    你的班级提供:

    var animator: SolutionAnimator!
    

    但是SolutionAnimator! 不符合AnimatorSolutionAnimator 确实如此。删除!

    如果您出于某种技术原因无法删除 !(例如,如果这是从情节提要中实例化的,则可能无法使用),那么您只需隐藏 ! 以便正确符合协议:

    private var _animator: SolutionAnimator!
    var animator: SolutionAnimator {
        get { return _animator }
        set { _animator = newValue }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多