Zack Shapiro Zack Shapiro - 3 months ago 76
Swift Question

Swift – Using popViewController and passing data to the ViewController you're returning to

I have an optional

variable called
on my first view controller which is called
, and I'm popping from
back to

Before I pop, I want to set the bool to true. Seems wrong to instantiate another view controller since
is in memory.

What's the best way to do this? I'm not using storyboards, if that's important for your answer.

Thanks for your help


So I figured it out, based mostly from this post –

In SecondViewController, above the class declaration, add this code:

protocol SecondVCDelegate {
    func didFinishSecondVC(controller: SecondViewController)

Then inside of SecondViewContoller add a class variable:

var delegate: MeditationVCDelegate! = nil

Then inside of your function that your button targets, add this:


What we're doing here is doing the pop in SecondViewController, and not passing any data, but since we've defined a protocol, we're going to use that in ViewController to handle the data.

So next, in ViewController, add the protocol you defined in SecondViewController to the list of classes ViewController inherits from:

class ViewController: UIViewController, SecondVCDelegate { ... your code... }

You'll need to add the function we defined in the new protocol in order to make the compiler happy. Inside of ViewController's class, add this:

func didFinishSecondVC(controller: SecondViewController) {
    self.myBoolVar = true

In SecondViewController where we're calling didFinishSecondVC, we're calling this method inside of the ViewController class, the controller we're popping to. It's similar to if we wrote this code inside of SecondViewController but we've written it inside of ViewController and we're using a delegate to manage the messaging between the two.

Finally, in ViewController, in the function we're targeting to push to SecondViewController, add this code:

let secondVC = secondViewController()
secondVC.delegate = self
self.navigationController?.pushViewController(secondVC, animated: true)

That's it! You should be all set to pass code between two view controllers without using storyboards!