Here is my solution in Swift 3
1) Create a protocol inside the SecondController.swift file. We preferably create the protocol from where we will be getting data from.
protocol Protocol {
func passingDataBack(withString: String)
}
2) Create a variable of type Protocol
var proto: Protocol!
3) Switch to the ViewController.swift file and inherit the Protocol we made from the SecondController.swift file.
class ViewController: UIViewController, Protocol {
}
4) We then want to conform to the Protocol we made by creating the function we made
func passingDataBack(withString: String) {
// withString will return the value that has been passed from our SecondController class
self.title = withString
}
5) Use the prepareForSegue method and segue to the SecondController class
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as? SecondController
vc?.proto = self //This line will instantiate the protocol to our ViewController class
}
6) Go back to our SecondController.swift file and use the didSelectRow method and pass our data
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
proto.passingDataBack(withString: items[indexPath.row]) //Call the protocol and the function then pass our data.
_ = self.navigationController?.popViewController(animated: true) //This will pop back to our previous controller.
}
* Important Things To Remember!!! *
You must set the protocol from controllerB to instantiate to controllerA when switching from controllerA to controllerB
In our example, we moved from ViewController to SecondController. We instantiate our protocol from our SecondController by doing
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as? SecondController
vc?.proto = self //This line will instantiate the protocol to our ViewController class
}
If you do not do this, you will get a Thread 001 error on this line
proto.passingDataBack(withString: items[indexPath.row]) //Call the protocol and the function then pass our data.
Source code Github