Swift popToViewController Swift popToViewController swift swift

Swift popToViewController


let controllers = self.navigationController?.viewControllers              for vc in controllers! {                if vc is YourVC {                  _ = self.navigationController?.popToViewController(vc as! YourVC, animated: true)                }             }


I know this is old, but it's like what Saqib said, you can't pop to a viewcontroller that doesn't exist yet.

A lot of the answers here seem to be from people that didn't read your question, just the title. I'll leave this code here in case it helps anyone.

let vcIndex = self.navigationController?.viewControllers.indexOf({ (viewController) -> Bool in    if let _ = viewController as? ComposeViewController {        return true    }    return false})let composeVC = self.navigationController?.viewControllers[vcIndex!] as! ComposeViewControllerself.navigationController?.popToViewController(composeVC, animated: true)


There's a method that lets you get access to an array of all the ViewControllers on the current stack, and you can capture the one you want by using its index, for instance:

let switchViewController = self.navigationController?.viewControllers[1] as! ComposeViewControllerself.navigationController?.popToViewController(switchViewController, animated: true)