Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61870

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)

Upvotes: 0

Views: 58

Answers (2)

Raja Kishan
Raja Kishan

Reputation: 19024

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

Upvotes: 0

Sweeper
Sweeper

Reputation: 274320

As far as the compiler is concerned, classType isn't a type like String or Int. 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.

We need a type that is known at compile time. We can pass such a type parameter with 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.

Upvotes: 3

Related Questions