Make Segue programmatically in Swift

Kahsn picture Kahsn · Feb 11, 2016 · Viewed 27.4k times · Source

I have two VCs: VC1 and VC2. In VC1, I have a finish button which I programmatically made and a result array I want to pass to VC2.

I know how to make Segue in Storyboard, but I cannot do that at this moment since the finish button is programmatically made.

If I want to pass result array using segue, is there a way to make the segue programmatically? If this is not possible, should I just present VC2 using presentViewController and set a delegate to pass the result array?

Answer

dehlen picture dehlen · Feb 11, 2016

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.