The delegate pattern is commonly used to situations such as: Screen A opens screen B and at some point screen B needs to communicate back to screen A. The solution is to make screen A the delgate of screen B, so that B can send it’s messages to A whenever it needs to. This is the preferred way of screen/view communication. The principle of screens being independent of each others but yet still able to communicate is called loose coupling and is considered good software design practice. Delegates go hand-in-hand with protocols which is a prominent feature of the Swift language. For an example of setting up protocols and delegates see below

protocol AddItemViewControllerDelegate: class {
  func addItemViewControllerDidCancel(controller: AddItemViewController)
  func addItemViewController(controller: AddItemViewController, didFinishAddingItem item: ChecklistItem)
}

This defines the AddItemViewController Delegate protocol. In Swift a protocol is simply a name for a group of methods. A protocol doesn’t implement any of the methods it declares. It just says: any object that conforms to this protocol must implement methods, X,Y, and Z.

The two methods listed in the example are: addItemViewControllerDidCancel() addItemViewController(didFinishAddingItem) The first oneis for when the user presses Cancel, the second one is for when they press Done. In that case, the didFinishAddingItem paramter passes along the new ChecklistItem object. To make the ChecklistViewController conform to this created protocol, it must provide implementations of these two methods. From then one can refer to the ChecklistViewContorller using just the protocol name.

Inside the AddItemViewController you can write var delegate: AddItemViewController Delegate

The variable delegate is nothing more than a reference to some object that implements the methods of this protocol. You can send messages to the object from the delegate variable, without knowing what kind of object it really is.

Swift has a shorthand for skipping the work when delegate is not set: delegate?.addItemViewControllerDidCancel(self) Here the ? tells Swift not to send the message if delegate is nil. You can read this as, “Is there a delegate?” Then send the message. This is known as optional chaining and is used a lot within Swift.

Five Steps to Delegates

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  // 1
  if segue.identifier == "AddItem" {
    // 2
    let navigationController = segue.destinationViewController as! UINavigationController
    // 3
    let controller = navigationController.topViewController as! AddItemViewController
    // 4
    controller.delegate = self
  }
}

This is what the prepareForSegue does step-by-step