Search code examples
iosiphoneswiftsegueunwind-segue

unwind segue pass data to different viewcontrollers


I have an app which have 4 different forms. these forms can be completed by clicking the different questions and being lead to a viewcontroller which holds the options. lets call this the OptionViewController. Now I have 4 different forms with different options but all using OptionViewController to pull data from the database, I need to unwind the segue and pass data.

Since there might be 4 different view controllers it might be coming from, I need to make sure that the information is passed properly, i.e. identify if the destinationviewcontroller the unwindsegue is performing the first, second, third or fourth viewcontroller.

I thought I might do something like this

        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.

    if segue.identifier == "optionSelected" {

        if segue.destinationViewController == FirstViewController {

             //pass data

        } else if segue.destinationViewController == SecondViewController {
             //pass data
        }

    }
}

But obviously I cannot perform segue.destinationViewController == FirstViewController

What should I actually be doing? Or should i just create one OptionViewController for every form, which would solve my problem, but I am not sure if overall the app performance will drop due to the increase of view controllers

Thanks for any help in advance


Solution

  • To test if the destination view controller is of a specific class, use the Swift keyword is:

    if segue.destinationViewController is FirstViewController {
    

    Alternatively, you can assign the viewController to a variable using optional binding with an optional cast:

    if let dvc = segue.destinationViewController as? FirstViewController {
        // dvc will have type FirstViewController so you can access specific
        // properties of FirstViewController using dvc
    }