18

I am calling a segue programatically, Can any one please help me how can pass parameters ?

@IBAction func update(sender: AnyObject) {

    self.performSegueWithIdentifier("showUpdate", sender: nil)
}
venkat kotu
  • 193
  • 1
  • 1
  • 6

3 Answers3

33

Swift 4:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ExampleSegueIdentifier" {
        if let destinationVC = segue.destination as? ExampleSegueVC {
            destinationVC.exampleStringProperty = "Example"
        }
    }
}

Swift 3:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "ExampleSegueIdentifier" {
            if let destinationVC = segue.destinationViewController as? ExampleSegueVC {
                destinationVC.exampleStringProperty = "Example"
            }
        }
    }
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Ryan Huebert
  • 613
  • 1
  • 6
  • 8
  • I would suggest to simply use `let destinationVC = segue.destination as! ExampleSegueVC` instead of that `if let` construction with `as?`. In this case you will fail fast if you forgot to assign `ExampleSegueVC` class to your view controller. – interrupt Jun 02 '19 at 08:02
25

The performSegueWithIdentifier method takes two arguments, 1. the segue identifier, 2. the parameter you are passing which is of type AnyObject?

@IBAction func update(sender: AnyObject) {

  self.performSegueWithIdentifier("showUpdate", sender: sender)
}

Then in the prepareForSegue method, you check the segue identifier and cast the sender parameter to the type you passed in earlier.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showUpdate" {
        guard let object = sender as? ObjectToUpdateType else { return }
        let dvc = segue.destinationViewController as! DestinationViewController
        dvc.objectToInject = object
    }
}
Ahmed Onawale
  • 3,992
  • 1
  • 17
  • 21
  • Really this is the best answer I've seen. All others expect you to set a var property inside of your viewController class for the data you want to pass to the segue once which I think is a little overkill. – Mike R Aug 08 '20 at 12:48
2

Prepare for segue can pass data along.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if (segue.identifier == "showUpdate") {

            if let vc: DestinationVC = segue.destinationViewController as? DestinationVC {
                  vc.variable = variableToPass
            }

        }
 }
D. Greg
  • 991
  • 1
  • 9
  • 21