Protocols and Delegates

This tutorial takes you through a simple application with two view controllers. Once which collects some data, and one which displays the data. A protocol and delegation is used to pass the data between the two view controllers.

  1. Fork or download the starter project from GitHub and open it in Xcode
  2. Open the DataCollectionViewController file
  3. This view controller will be used to collect some data (a String) from the user.

    Ideally it should be able to return that data to any view controller, or indeed an instance of another type of class, so we dont want it to have a reference to any specific view controller in its code, as this would impede reusability. Instead, we want to be able to delegate responsibility to any view controller capable of receiving the data

  4. Within the DataCollectionViewController file, but outside the class, add the following code:

    protocol DataCollectionViewControllerDelegate {
        func dataUpdated(userText: String)

    Any class adopting this prtocol would be able to be notified when the data in a DataCollectionViewController is updated

  5. The next stage is to configure the DataCollectionViewController so it can has a reference to its delegate. Add a property to the class as follows:
    var delegate : DataCollectionViewControllerDelegate?
    This property will represent the delegate. The delegate is an optional as it might not exist
  6. Next add code in the doneButtonPressed() method to notify the delegate of the new data, before the view is dismissed:
    delegate?.dataUpdated(userText: textField.text!)
    Note that the method would only be called if the delegate exists (the ? ensures this)
  7. Next the ViewController (which displays the data) to be configured to adopt the DataCollectionViewControllerDelegate protocol. Open that file and modify the delcaration of the class to that it adops the delegate as follows:
    class ViewController: UIViewController, DataCollectionViewControllerDelegate {
        //code etc.
  8. Xcode will display a warning stating that the View controller doesn't conform to the protocol 'DataCollectionViewControllerDelegate' and ask us if we want to add method stubs. Choose the 'fix' option on the warning which will add the following code automatically
    func dataUpdated(userText: String) {
  9. Modify the body of that method stub to update the view with the data as follows:
    displayLabel.text = userText
  10. Finally, we need to notify the DataCollectionViewController that the ViewController class is its delegate. Add the following in the prepare(for segue, sender) method
    if let destination = segue.destination as? DataCollectionViewController {
        destination.delegate = self
  11. Test your code, setting break points at the various methods you've implemented, to see how the code works.