O.Naeem O.Naeem - 1 year ago 76
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

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

I have a textfield in
and when you type something in it and press a button, I want to pass it to a label in
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

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.


Answer Source

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() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download