I used the Objective-C code below to pop a specific ViewController.
for (UIViewController *controller in self.navigationController.
I prefer a "real generic" and more functional approach.
So I came up with following UINavigationController extension functions. You can also use the first function, for anything else, where you just need to access a specific VC in the navigation stack.
Extensions
extension UINavigationController {
func getViewController(of type: T.Type) -> UIViewController? {
return self.viewControllers.first(where: { $0 is T })
}
func popToViewController(of type: T.Type, animated: Bool) {
guard let viewController = self.getViewController(of: type) else { return }
self.popToViewController(viewController, animated: animated)
}
}
Usage
self.navigationController?.popToViewController(of: YourViewController.self, animated: true)
This should work at least in Swift 4 and 5.