Extending Protocols in Swift: Conformance with Extensions

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

by The Captain

on
March 23, 2024

Working with Extensions for Protocol Conformance in Swift

Extensions in Swift allow you to add new functionality to existing types, including protocols. In this tutorial, we will explore how to use extensions to conform to protocols in Swift.

Creating Protocol

First, let's create a protocol called EquatableProtocol that requires conforming types to implement an equality check method:

protocol EquatableProtocol {
    func isEqual(to other: Self) -> Bool
}

Extending Struct to Conform to Protocol

Next, let's create a struct called MyStruct and extend it to conform to the EquatableProtocol:

struct MyStruct {
    var value: Int
}

extension MyStruct: EquatableProtocol {
    func isEqual(to other: MyStruct) -> Bool {
        return self.value == other.value
    }
}

Now, the MyStruct struct conforms to the EquatableProtocol by implementing the isEqual(to:) method.

Using Protocol Conformance

We can now use the protocol conformance in our code to compare instances of the MyStruct struct:

let myStruct1 = MyStruct(value: 10)
let myStruct2 = MyStruct(value: 10)

if myStruct1.isEqual(to: myStruct2) {
    print("Instances are equal")
} else {
    print("Instances are not equal")
}

When we run this code, it will print "Instances are equal" because both instances have the same value and the isEqual(to:) method returns true.

Summary

In this tutorial, we learned how to use extensions to add protocol conformance to existing types in Swift. This technique can be useful for organizing and extending the functionality of your code.