Delegates & Protocols

Delegates and protocols are concepts commonly used in the Swift programming language, which is primarily used for iOS and macOS app development. They are fundamental building blocks for creating flexible and extensible code by enabling communication between different parts of an application.

  1. Delegates:
    • A delegate is a design pattern that allows one object to act on behalf of another object or to respond to certain events or data changes.
    • In Swift, delegates are often defined using protocols. A protocol declares a set of methods that another class or struct can adopt. The class or struct that adopts the protocol is then referred to as the delegate.
    • Delegates are commonly used to implement the "Delegate Pattern," where one object delegates certain responsibilities or tasks to another object.

Example:

protocol MyDelegate {
    func didSomething()
}

class MyClass {
    var delegate: MyDelegate?

    func performTask() {
        // Do some work
        delegate?.didSomething()
    }
}

In this example, MyClass has a delegate of type MyDelegate. When performTask() is called, it triggers the didSomething() method on the delegate if it's implemented.

  1. Protocols:Example:
    • Protocols define a blueprint of methods, properties, and other requirements that a conforming type must implement. They are a way to define a set of rules or capabilities without specifying how they are implemented.
    • Types (classes, structs, or enums) can adopt one or more protocols, providing a common interface for diverse types to work together.
    • Protocols are crucial for achieving polymorphism and creating code that is easy to extend and maintain.
protocol Shape {
    var area: Double { get }
    func describe()
}

class Circle: Shape {
    var radius: Double

    init(radius: Double) {
        self.radius = radius
    }

    var area: Double {
        return Double.pi * radius * radius
    }

    func describe() {
        print("I am a circle with radius \(radius)")
    }
}

class Square: Shape {
    var sideLength: Double

    init(sideLength: Double) {
        self.sideLength = sideLength
    }

    var area: Double {
        return sideLength * sideLength
    }

    func describe() {
        print("I am a square with side length \(sideLength)")
    }
}

In this example, Circle and Square both conform to the Shape protocol, providing a consistent interface (area and describe()) while allowing for different implementations.

In summary, delegates and protocols in Swift are powerful tools for creating modular, extensible, and maintainable code by facilitating communication between different parts of an application and defining common interfaces for diverse types.