Chapters

Hide chapters

UIKit Apprentice

Third Edition · iOS 18 · Swift 5.10 · Xcode 16

My Locations

Section 3: 11 chapters
Show chapters Hide chapters

Store Search

Section 4: 13 chapters
Show chapters Hide chapters

13. Delegates & Protocols
Written by Fahim Farook

Heads up... You’re accessing parts of this content for free, with some sections shown as ckdilmkun text.

Heads up... You’re accessing parts of this content for free, with some sections shown as lxjeqrmil text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

You now have an Add Item screen showing a keyboard that lets the user enter text. The app also properly validates the input so that you’ll never end up with text that is empty.

But how do you get this text into a new ChecklistItem object that you can add to the items array on the Checklists screen? That is the topic that this chapter will explore.

Add new ChecklistItems

In order for a new item addition to work, you’ll have to get the Add Item screen to notify the Checklist View Controller of the new item addition. This is one of the fundamental tasks that every iOS app needs to do: sending messages from one view controller to another.

Sending a ChecklistItem object to the screen with the items array
Sending a ChecklistItem object to the screen with the items array

The messy way

Exercise: How would you tackle this problem? The done() method needs to create a new ChecklistItem object with the text from the text field (easy), then add it to the items array and the table view in ChecklistViewController (not so easy).

Heads up... You’re accessing parts of this content for free, with some sections shown as dlkuzfsep text.

Heads up... You’re accessing parts of this content for free, with some sections shown as dvzavncaj text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
class AddItemViewController: UITableViewController, . . . {

  // This variable refers to the other view controller
  var checklistViewController: ChecklistViewController

  @IBAction func done() {
    // Create the new checklist item object
    let item = ChecklistItem()
    item.text = textField.text!

    // Directly call a method from ChecklistViewController
    checklistViewController.add(item)
  }
}
Screen A knows all about screen B, but B knows nothing of A
Njkiif E pnahx oyk akeag xsliuj C, naz S vkihc xuhdayf es O

The delegate way

You’ve already seen delegates in a few different places: the table view has a delegate that responds to taps on the rows; the text field has a delegate that you used to validate the length of the text; and the app also has things named AppDelegate and SceneDelegate — check the project navigator.

Heads up... You’re accessing parts of this content for free, with some sections shown as jhgyfdvew text.

Heads up... You’re accessing parts of this content for free, with some sections shown as jkxyrhxoq text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
Screen A launches screen B and becomes its delegate
Qqzoob A yaejjtab xcsoaw Z ujf zoduvoc eyl zewaroke

This is what Screen B sees: only the delegate part, not the rest of screen A
Kyev ut tpec Slnaog R miig: uscy tdo sojesije todj, bih pnu cufp eq blyeor E

The delegate protocol

➤ At the top of AddItemViewController.swift, add the following after the import line, but before the class line — it is not part of the AddItemViewController object:

protocol AddItemViewControllerDelegate: AnyObject {
  func addItemViewControllerDidCancel(
    _ controller: AddItemViewController)
  func addItemViewController(
    _ controller: AddItemViewController,
    didFinishAdding item: ChecklistItem
  )
}

Heads up... You’re accessing parts of this content for free, with some sections shown as lnxefggoc text.

Heads up... You’re accessing parts of this content for free, with some sections shown as dkgurbdut text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Protocols

In Swift, a protocol doesn’t have anything to do with computer networks or meeting royalty. It is simply a name for a group of methods.

Heads up... You’re accessing parts of this content for free, with some sections shown as phwonqcyf text.

Heads up... You’re accessing parts of this content for free, with some sections shown as jddydpkyj text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
var delegate: AddItemViewControllerDelegate

Notify the delegate

You’re not done yet in AddItemViewController.swift. The view controller needs a property that it can use to refer to the delegate.

weak var delegate: AddItemViewControllerDelegate?

Heads up... You’re accessing parts of this content for free, with some sections shown as dxwipfcul text.

Heads up... You’re accessing parts of this content for free, with some sections shown as nnpudxlod text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
@IBAction func cancel() {
  delegate?.addItemViewControllerDidCancel(self)
}

@IBAction func done() {
  let item = ChecklistItem()
  item.text = textField.text!

  delegate?.addItemViewController(self, didFinishAdding: item)
}

Heads up... You’re accessing parts of this content for free, with some sections shown as ndpogcnyf text.

Heads up... You’re accessing parts of this content for free, with some sections shown as tpvawdgyg text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Optionals

I mentioned a few times that variables and constants in Swift must always have a value. In other programming languages the special symbol nil or NULL is often used to indicate that a variable has no value. This is not allowed in Swift for normal variables.

weak var delegate: AddItemViewControllerDelegate?

Heads up... You’re accessing parts of this content for free, with some sections shown as tfvybrbig text.

Heads up... You’re accessing parts of this content for free, with some sections shown as pvdejmxej text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
delegate?.addItemViewControllerDidCancel(self)

Heads up... You’re accessing parts of this content for free, with some sections shown as dmlyrqzod text.

Heads up... You’re accessing parts of this content for free, with some sections shown as hxzemvhof text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Conform to the delegate protocol

Before you can give AddItemViewController its delegate, you first need to make the ChecklistViewController suitable to play the role of delegate.

class ChecklistViewController: UITableViewController, AddItemViewControllerDelegate {
Xcode warns about not conforming to protocol
Jreni hubfm uxoev lim tihdorreth mu kzanuwij

// MARK: - Add Item ViewController Delegates
func addItemViewControllerDidCancel(
  _ controller: AddItemViewController
) {
  navigationController?.popViewController(animated: true)
}

func addItemViewController(
  _ controller: AddItemViewController,
  didFinishAdding item: ChecklistItem
) {
  navigationController?.popViewController(animated: true)
}

Heads up... You’re accessing parts of this content for free, with some sections shown as bjrehcsom text.

Heads up... You’re accessing parts of this content for free, with some sections shown as hckyhfmon text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Heads up... You’re accessing parts of this content for free, with some sections shown as chraxtdef text.

Heads up... You’re accessing parts of this content for free, with some sections shown as clmylslej text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
// MARK: - Navigation
override func prepare(
  for segue: UIStoryboardSegue,
  sender: Any?
) {
  // 1
  if segue.identifier == "AddItem" {
    // 2
    let controller = segue.destination as! AddItemViewController
    // 3
    controller.delegate = self
  }
}

Set the segue identifier

See the segue identifier mentioned in the code above? Where was it set? The answer is, that it wasn’t! We need to set the identifier in order for the above code to work. If you forget to, then you won’t get the delegate set up correctly when segueing to the Add Item screen.

Heads up... You’re accessing parts of this content for free, with some sections shown as qhmimmsax text.

Heads up... You’re accessing parts of this content for free, with some sections shown as jclijjfuc text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
Naming the segue between the Checklists scene and the Add Item scene
Yukiqq cce fegoe keypaag mgo Dgujktutyq plovo ulq hju Ehf Uqez yxuho

Add new to-do items

➤ Change the implementation of the didFinishAdding delegate method in ChecklistViewController.swift to the following:

func addItemViewController(
  _ controller: AddItemViewController,
  didFinishAdding item: ChecklistItem
) {
  let newRowIndex = items.count
  items.append(item)

  let indexPath = IndexPath(row: newRowIndex, section: 0)
  let indexPaths = [indexPath]
  tableView.insertRows(at: indexPaths, with: .automatic)
  navigationController?.popViewController(animated:true)
}

Heads up... You’re accessing parts of this content for free, with some sections shown as blbevcneg text.

Heads up... You’re accessing parts of this content for free, with some sections shown as hnkugpbeh text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
You can finally add new items to the to-do list
Sai yoy sicermm arn guq ixavg si ndo qi-ve rogr

Weak

I still owe you an explanation about the weak keyword. Relationships between objects can be weak or strong. You use weak relationships to avoid what is known as an ownership cycle.

Heads up... You’re accessing parts of this content for free, with some sections shown as pjmufzbab text.

Heads up... You’re accessing parts of this content for free, with some sections shown as mlwokhzex text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now
U X bgbaxv zslidk

E R vxgonc seid

Heads up... You’re accessing parts of this content for free, with some sections shown as tfdescpuf text.

Heads up... You’re accessing parts of this content for free, with some sections shown as kgricmbek text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2025 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as wqfojvsum text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now