Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a reference to previous viewController in Swift?

Tags:

uikit

swift

Can somebody help me get a reference of the previous viewController in the UINavigationController stack? I'm sure it's straight forward but I'm a bit tapped at the moment.

enter image description here

like image 906
Aaronium112 Avatar asked Jul 21 '16 00:07

Aaronium112


People also ask

How do I pop a ViewController in Swift?

You can do it by selecting the View Controller in Storyboard editor and clicking Editor -> Embed In -> Navigation Controller. Also make sure that you have your Storyboard Entry Point (the arrow that indicates which view controller is presented first) either pointing to Navigation Controller or before it.


1 Answers

First thing array always starts with index 0, So to access previous you need to minus 2. Also the above code of your will crash with Array index out of Range, if your the index of access object is less than your count. so check your condition like this

let count = viewControllers?.count
if count > 1 {
    if let setVC = viewControllers?[count -2] as? SWSetVC {
        //Set the value
    }
}
like image 77
Nirav D Avatar answered Oct 07 '22 23:10

Nirav D