Passing data back from view controllers Xcode

You need to use a delegate. Here is an example how do use a delegate in Swift.

On your first ViewController, set your delegate when you load the second VC:

For example, if you are using the Storyboard Editor:

var secondViewController = (segue.destinationViewController.visibleViewController as  MySecondViewControllerClass)
secondViewController.delegate = self

Write a Protocol and define a func to write you values back

For example, create a file called “Protocol.swift” and write something like that:

protocol writeValueBackDelegate {
    func writeValueBack(value: String)
}

Add the function to your FirstViewController

func writeValueBack(value: String) {
   // Or any other function you need to transport data
}

And to your ViewControllerClass

class ViewController: UIViewController, writeValueBackDelegate

The above line will not work if you have not implemented all of the methods in ViewController that you defined in your protocol file.

Go to the Second View Controller, and add the delegate here:

class SecondViewController: ViewController {

    // Delegate for FirstViewController
    // Declare as weak to avoid memory cycles
    weak var delegate: writeValueBackDelegate?
}

On your Second View Controller, you can now use this to call the func in the first View Controller an pass data.

delegate?.writeValueBack("That is a value")

Leave a Comment