Implementing Protocols and Delegates

Tutorial 3 of 5

1. Introduction

1.1 Brief explanation of the tutorial's goal

This tutorial aims to teach you how to use protocols and delegates in Swift. Protocols and delegation are powerful design patterns in Swift that allow you to pass data or events between classes in a clean and flexible way.

1.2 What the user will learn

By the end of this tutorial, you will be able to:
- Define and implement protocols
- Understand and use delegates
- Improve your code design through protocols and delegation

1.3 Prerequisites

To follow this tutorial, you should have a basic understanding of Swift and Object-Oriented Programming concepts. Familiarity with Xcode is also helpful, but not necessary.

2. Step-by-Step Guide

2.1 Protocols

A protocol is a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. It's like an interface in other languages. Protocols can be adopted by classes, structs, and enums.

Define a protocol using the protocol keyword. Here's a protocol named Identifiable:

protocol Identifiable {
    var id: String { get set }
}

2.2 Delegates

Delegation is a design pattern that enables a class or structure to delegate some of its responsibilities to an instance of another type. It's a way of customizing the behavior of a class without subclassing.

Here's a basic example of delegation:

protocol TaskDelegate {
    func taskDidFinish()
}

class Task {
    var delegate: TaskDelegate?

    func finish() {
        // some task finishing code here...
        delegate?.taskDidFinish()
    }
}

3. Code Examples

3.1 Protocol Example

Defining a protocol:

protocol CanFly {
    func fly()
}

class Bird {
    var name: String

    init(name: String) {
        self.name = name
    }
}

class Eagle: Bird, CanFly {
    func fly() {
        print("\(name) can fly!")
    }
}

let eagle = Eagle(name: "Eagle")
eagle.fly() // prints "Eagle can fly!"

3.2 Delegate Example

Using delegation to pass data between classes:

protocol DataPassingDelegate {
    func passData(data: String)
}

class FirstClass {
    var delegate: DataPassingDelegate?

    func passData() {
        delegate?.passData(data: "Hello from FirstClass!")
    }
}

class SecondClass: DataPassingDelegate {
    func passData(data: String) {
        print(data)
    }
}

let firstClass = FirstClass()
let secondClass = SecondClass()

firstClass.delegate = secondClass
firstClass.passData() // prints "Hello from FirstClass!"

4. Summary

In this tutorial, you learned about protocols and delegates, both powerful design patterns in Swift. You learned how to define and implement protocols, how to use delegates, and how to use these patterns to improve your code design.

5. Practice Exercises

5.1 Exercise 1

Define a protocol CanRun and a class Dog that adopts this protocol. The protocol should have a run method that prints " can run!".

5.2 Exercise 2

Create a protocol OrderDelegate with a method orderDidFinish. Then create a class Order that has a delegate of type OrderDelegate. When the finish method on an Order instance is called, it should notify the delegate.

5.3 Exercise 3

Expand the second exercise to pass the Order instance to the delegate so it knows which order finished.

5.4 Solutions

5.4.1 Solution to Exercise 1

protocol CanRun {
    func run()
}

class Dog: CanRun {
    var name: String

    init(name: String) {
        self.name = name
    }

    func run() {
        print("\(name) can run!")
    }
}

let dog = Dog(name: "Buddy")
dog.run() // prints "Buddy can run!"

5.4.2 Solution to Exercise 2

protocol OrderDelegate {
    func orderDidFinish()
}

class Order {
    var delegate: OrderDelegate?

    func finish() {
        delegate?.orderDidFinish()
    }
}

class Customer: OrderDelegate {
    func orderDidFinish() {
        print("My order is finished!")
    }
}

let order = Order()
let customer = Customer()

order.delegate = customer
order.finish() // prints "My order is finished!"

5.4.3 Solution to Exercise 3

protocol OrderDelegate {
    func orderDidFinish(order: Order)
}

class Order {
    var delegate: OrderDelegate?
    var id: Int

    init(id: Int) {
        self.id = id
    }

    func finish() {
        delegate?.orderDidFinish(order: self)
    }
}

class Customer: OrderDelegate {
    func orderDidFinish(order: Order) {
        print("My order \(order.id) is finished!")
    }
}

let order = Order(id: 1)
let customer = Customer()

order.delegate = customer
order.finish() // prints "My order 1 is finished!"

Keep practicing with different protocols and delegate scenarios to get a deeper understanding. Happy coding!