iOS how to simple return back to previous presented/pushed view controller programmatically?

How to return back to previous view controller programmatically? I found this answer, but there is an example that demonstrate how to go back if we have navigation stack:

navigationController?.popViewControllerAnimated(true)

It’s ok in case my queue of controllers based on navigation controller. But usually we use storyboard where we specify segue that marked with keyword Show that means we don’t care about navigation push or present new view controllers. So in this case I presume there is only option with unwind view controller via segue, but maybe there is some simple call that I can do programmatically to go back to my previous view controller without checking if my stack of view controllers contain UINavigationController or not.

  • Correct and secure manner of storing in-app-purchases
  • How to split string into substrings on iOS?
  • AVAudioEngine crashes when I unplug headphones during a call
  • AFNetworking and jSON
  • How to implement a physical effect in SimCity 5, that a building swings when it is being moved?
  • ApplePay PKPaymentAuthorizationViewController always shows processing
  • I am looking for something simple like self.performSegueToReturnBack.

    2 Solutions Collect From Internet About “iOS how to simple return back to previous presented/pushed view controller programmatically?”

    You can easily extend functionality of any inbuilt classes or any other classes through extensions. This is the perfect use cases of extensions in swift.

    You can make extension of UIViewController like this and use the performSegueToReturnBack function in any UIViewController

    Swift 2.0

    extension UIViewController {
        func performSegueToReturnBack()  {
            if let nav = self.navigationController {
                nav.popViewControllerAnimated(true)
            } else {
                self.dismissViewControllerAnimated(true, completion: nil)
            }
        }
    }
    

    Swift 3.0

    extension UIViewController {
        func performSegueToReturnBack()  {
            if let nav = self.navigationController {
                nav.popViewController(animated: true)
            } else {
                self.dismiss(animated: true, completion: nil)
            }
        }
    }
    

    Note:

    Someone suggested that we should assign _ = nav.popViewControllerAnimated(true) to an unnamed variable as compiler complains if we use it without assigning to anything. But I didn’t find it so.

    Best answer is this:
    _ = navigationController?.popViewController(animated: true)

    Taken from here: https://stackoverflow.com/a/28761084/2173368