Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Delegation Pattern in Swift
Written by Team Kodeco

In Swift, the delegation pattern is a way to separate responsibilities between objects. The delegation pattern involves:

  • One object, known as the delegate is responsible for handling certain events or actions
  • Another object, known as the delegator, is responsible for initiating those events or actions.

Here’s an example of how to use the delegation pattern in Swift:

protocol SchoolDelegate: AnyObject {
  func classDidStart()
  func classDidEnd()
}

class School {
  weak var delegate: SchoolDelegate?
  
  func startClass() {
    print("Class started.")
    delegate?.classDidStart()
  }
  
  func endClass() {
    print("Class ended.")
    delegate?.classDidEnd()
  }
}

class Student: SchoolDelegate {
  func classDidStart() {
    print("Opening notebook.")
  }
  
  func classDidEnd() {
    print("Packing up backpack.")
  }
}

let student = Student()
let school = School()
school.delegate = student
school.startClass()
school.endClass()
// Output: Class started.
//         Opening notebook.
//         Class ended.
//         Packing up backpack.

In this example, the School class is the delegator, responsible for starting and stopping classes. The Student class is the delegate, responsible for handling certain events when classes start or stop, such as opening their notebook or packing up their backpack.

© 2024 Kodeco Inc.