O.Naeem O.Naeem - 1 month ago 6
Swift Question

How to pass data to a previous ViewController in Swift (Cocoa Application)

Passing data to the next viewController is simple and straightforward, and can be done using

prepareSegue
method. However, I can't understand how to pass data to a previous viewController in Swift(Cocoa Application)

I have a textfield in
viewControllerB
and when you type something in it and press a button, I want to pass it to a label in
viewControllerA
and instead of opening the viewControllerA in a new window, I just want the
viewController B
to be dismissed and the passed data to be visible on the
viewControllerA
.

That's all there is to it. I have been stuck on it for the past 48 hours. Any help on this will be appreciated.

Thanks!

Answer

You do this using delegates. Example:

protocol NextProtocol: class {
    func sendBack(value: Int)
}

class Previous: NextProtocol {
    func sendBack(value: Int) {
        print("I have received \(value))
    }

    func prepareSegue(...) {
        // get next instance
        var next: Next
        next.delegate = self
    }
}

class Next {
   weak var delegate: NextProtocol?

   func someMethod() {
       delegate?.sendBack(5)
   }  
}