Sending data with Segue with Swift

Set values from Any ViewController to a Second One using segues

Like this:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if(segue.identifier == "yourIdentifierInStoryboard") {

        let yourNextViewController = (segue.destinationViewController as yourNextViewControllerClass)
        yourNextViewController.value = yourValue

And in your yourNextViewController class.

class yourNextViewControllerClass {

    var value:Int! // or whatever

You can call this also programmatically:

 self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)

Set values from your DestinationViewController back to your Primary (First) ViewController

1. Implement a protocol, for example create a file called protocol.swift.

    protocol changeUserValueDelegate {
       func changeUser(toValue:Bool)
    }

2. set the delegate on your second View

    class yourNextViewControllerClass {

    var delegate:changeUserValueDelegate?

3. set the delegate on load (prepareForSegue)

    if(segue.identifier == "yourIdentifierInStoryboard") {

        var yourNextViewController = (segue.destinationViewController as yourNextViewControllerClass)
        yourNextViewController.delegate = self

4. add Function to FirstViewController

    func changeUser(toValue:Bool) {
        self.currentUserValue = toValue
    }

5. call this function from your SecondViewController

     delegate?.changeUser(true)

6. Set the delegate in your FirstViewController

    class FirstViewController: UIViewController, ChangeUserValueDelegate {

Leave a Comment