Make Segue programmatically in Swift

You can do it like proposed in this answer: InstantiateViewControllerWithIdentifier.

Furthermore I am providing you the code from the linked answer rewritten in Swift because the answer in the link was originally written in Objective-C.

let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "identifier") as! SecondViewController

vc.resultsArray = self.resultsArray

EDIT:

Since this answer draws some attention I thought I provide you with another more failsafe way. In the above answer the application will crash if the ViewController with "identifier" is not of type SecondViewController. In Swift you can prevent this crash by using optional binding:

guard let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewControllerWithIdentifier("identifier") as? SecondViewController else {
    print("Could not instantiate view controller with identifier of type SecondViewController")
    return
}

vc.resultsArray = self.resultsArray
self.navigationController?.pushViewController(vc, animated:true)

This way the ViewController is pushed if it is of type SecondViewController. If can not be casted to SecondViewController a message is printed and the application remains on the current ViewController.


You can still create the segue in Interface Builder by dragging from VC1 to VC2 - just drag from/to the little yellow circle at the top of the VC. Give this segue a unique name in IB, and in your finish function you can call performSegueWithIdentifier:, pass in the name of your segue, and that's it. In the prepareForSegue method you can find out which segue is being performed by accessing segue.identifier, and if it's the segue in question you can get a pointer to segue.destinationViewController and pass your data on that way.

Tags:

Ios

Swift

Segue