An Advanced Swift Feature: Protocol Extensions

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
April 15, 2023

An Advanced Swift Feature: Protocol Extensions

Protocol extensions in Swift are a powerful feature that allows developers to add functionality to existing protocols without changing their definition. In this tutorial, we will explore what protocol extensions are, and how they can be used to improve the readability and reusability of your code.

What Are Protocol Extensions?

In Swift, protocols define a blueprint of methods, properties, and requirements that a conforming type must adopt. Protocol extensions, on the other hand, allow developers to add new functionality to existing protocols, without the need to modify the protocol definition. This means that any type that conforms to a protocol automatically gains access to the methods and properties defined in its protocol extension.

Using Protocol Extensions in Your Code

Let's take a look at an example of how protocol extensions can be used in a practical scenario. Suppose we have a protocol named `Calculable` that defines two required functions: `add()` and `subtract()`. We can also create a protocol extension that adds a third function to `Calculable` called `multiply()`. Here is what the code would look like:
protocol Calculable {
    func add(_ a: Int, _ b: Int) -> Int
    func subtract(_ a: Int, _ b: Int) -> Int
}

extension Calculable {
    func multiply(_ a: Int, _ b: Int) -> Int {
        return a * b
    }
}
As you can see, the `multiply()` function is added as an extension to `Calculable`, and any type that adopts the `Calculable` protocol will have access to this function. Now, let's say we have a struct `Calculator` that conforms to `Calculable`, and we want to use the `multiply()` function in our code. All we need to do is call the function on the `Calculator` instance:
struct Calculator: Calculable {
    func add(_ a: Int, _ b: Int) -> Int {
        return a + b
    }
    
    func subtract(_ a: Int, _ b: Int) -> Int {
        return a - b
    }
}

let calc = Calculator()
let result = calc.multiply(2, 3)
print(result) // Output: 6}
As you can see, we were able to use the `multiply()` function on our `Calculator` instance without having to define it within the `Calculator` struct itself.

Conclusion

In conclusion, protocol extensions are a powerful feature in Swift that allow developers to add new functionality to existing protocols without changing their definition. This can greatly improve the readability and reusability of your code, as well as make it easier to maintain and update. As you continue to work with Swift, consider using protocol extensions to streamline your code and enhance its functionality.