-1

I have a viewControllers array in navigationController, and I need to find the certain vc and call popToViewController method. But type checking always failed.

How can I check if a vc is of a given type in Swift?

func popToViewController<T>(vcClass: T.Type, animated: Bool) {
        guard let mainVc = self.rootController else {
            return
        }

        let controllers = mainVc.viewControllers
        for vc in controllers {
            if vc is T  {   // always is false 
                _ = mainVc.popToViewController(vc , animated: true)
            }
        }
}
self?.router.popToViewController(vcClass: ViewController1.Type.self, animated: true)
dev012
  • 21
  • 3

1 Answers1

0

Try this:

if type(of: vc) == T.self {
    _ = mainVc.popToViewController(vc , animated: true)
}

Or, if you want to check for a vc that can be cast into T:

if let _ = vc as? T {
    _ = mainVc.popToViewController(vc , animated: true)
}
pua666
  • 326
  • 1
  • 7