How to get a reference to previous viewController in Swift?

I use this extension on my projects:

extension Array where Iterator.Element == UIViewController {

    var previous: UIViewController? {
        if self.count > 1 {
            return self[self.count - 2]
        }
        return nil
    }

}

So you can check VCs in this way:

if self.navigationController?.viewControllers.previous is CustomVC {
    ...
} else {
    ...
}

You could also use this:

Swift 5

let i = navigationController?.viewControllers.firstIndex(of: self)
let previousViewController = navigationController?.viewControllers[i!-1]

Swift 3

 let i = navigationController?.viewControllers.index(of: self)
 let previousViewController = navigationController?.viewControllers[i!-1]

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
    }
}

Tags:

Uikit

Swift