Using callback closureblock passing data back

suggest change

This topic is a classical issue in iOS development, and its solutions vary, as other examples already show. In this example I’ll show another daily common use: passing data using a closure by adapting the delegate pattern example on this page into a callback closure.

One thing this method does better than the delegate pattern is that, instead of splitting the setup across two places (look at the delegate example on this page, prepareForSegue and userDidEnterInformation), it gathers them in prepareForSegue (I’ll show it). The samples below are Swift 2.

Start from Second View Controller

We must figure out how to use a callback before we can write it. This is why we start from the second view controller, since it’s where we use the callback: when we get the new text input, we call our callback, using the callback’s parameter as a way to pass data back to the first view controller. Notice that I said using the callback’s parameter. This is very important; novices (as I was) always overlook this and don’t know where to start to write a callback closure properly.

So in this case, we know that our callback only takes one parameter, text, and its type is String. Let’s declare it and make it a property, since we need to populate it from our first view controller.

I just comment out all the delegate part and keep it for comparison.

class SecondViewController: UIViewController {

    //weak var delegate: DataEnteredDelegate? = nil
    var callback: ((String?)->())?
    
    @IBOutlet weak var textField: UITextField!

    @IBAction func sendTextBackButton(sender: AnyObject) {
        
        //delegate?.userDidEnterInformation(textField.text!)
        callback?(textField.text)
        
        self.navigationController?.popViewControllerAnimated(true)
    }
}

Finish first view controller

All you have to do is pass the callback closure, and we are done. The closure will do the future work for us, since we already set it up in the second view controller.

Look how it makes our code shorter compared to the delegate pattern.

// no more DataEnteredDelegate
class FirstViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showSecondViewController" {
            let secondViewController = segue.destinationViewController as! SecondViewController
            // secondViewController.delegate = self
            secondViewController.callback = { text in self.label.text = text }
        }
    }

    // required method of our custom DataEnteredDelegate protocol
    //func userDidEnterInformation(info: String) {
    //    label.text = info
    //}
}

And lastly, some of you will be confused by the fact that we only pass the closure one way, from the first view controller to the second, with nothing coming directly back from the second view controller. How can we consider it a communicating tool? You should run it and prove it yourself. All I will say is that it’s the parameter, the callback closure’s parameter, that passes data back.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents