简体   繁体   English

如何在 Swift 中定义使用 class 类型作为参数的 function?

[英]How to define function that uses class type as a parameter in Swift?

I simply try to do the following:我只是尝试执行以下操作:

func popTo(classType: AnyClass, from context: UINavigationController?) {
    let controller = context?.viewControllers.first { $0 is classType }
    context?.popToViewController(controller, animated: true)
}

I need to use it like this:我需要像这样使用它:

popTo(SettingsViewController.self, from: navigationController)

As far as the compiler is concerned, classType isn't a type like String or Int .就编译器而言, classType不是StringInt之类的类型。 It's just the name of a parameter (which stores a type).它只是一个参数的名称(它存储一个类型)。 But the is operator expects a type (that can be resolved at compile time) on its RHS.但是is运算符期望其 RHS 上有一个类型(可以在编译时解析)。

We need a type that is known at compile time.我们需要一种在编译时已知的类型。 We can pass such a type parameter with generics:我们可以用 generics 传递这样一个类型参数:

func popTo<T>(classType: T.Type, from context: UINavigationController?) {
    if let controller = context?.viewControllers.first(where: { $0 is T }) {
        context?.popToViewController(controller, animated: true)
    }
}

You can also add the constraint T: AnyObject to more closely reflect the AnyClass (= AnyObject.Type ) in your original code, but you don't particularly have to.您还可以添加约束T: AnyObject以更接近地反映原始代码中的AnyClass (= AnyObject.Type ),但您不必特别这样做。

func popTo<T: UIViewController>(classType: T.Type, from context: UINavigationController?) {
    let controller = context?.viewControllers.first { $0 is T }
    context?.popToViewController(controller!, animated: true)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM