An Introduction to Protocols in Swift

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

by The Captain

on
April 14, 2023

An Introduction to Protocols in Swift

Protocols in Swift allow us to create a blueprint of methods, properties, and other requirements that can be implemented by classes, structs, and enums. In this tutorial, we will explore how to define and use protocols in Swift.

Defining a Protocol

Protocols are defined using the `protocol` keyword, followed by the protocol's name:
protocol MyProtocol {
    func method1()
    var property1: Int { get }
}
In the example above, we've defined a protocol named `MyProtocol`, which requires a method named `method1`, and a read-only property named `property1`.

Implementing a Protocol

To implement a protocol, a class, struct, or enum must conform to it using the `:` operator:
class MyClass: MyProtocol {
    func method1() {
        print("Method 1 called")
    }

    var property1: Int = 0
}
In the example above, we've created a class named `MyClass`, which conforms to the `MyProtocol` protocol. We've implemented the required method `method1`, and the required property `property1`.

Extending Protocols

Protocols can be extended just like classes, structs, and enums. This allows us to add new requirements to existing protocols:
extension MyProtocol {
    func method2() {
        print("Method 2 called")
    }
}
In the example above, we've extended the `MyProtocol` protocol to include a new method named `method2`. Any class, struct, or enum that conforms to `MyProtocol` will now have access to this new method.

Using Protocols as Types

Protocols can be used as types in Swift, allowing functions and properties to accept any object that conforms to a specific protocol. This is useful for creating flexible and reusable code:
func performAction(with object: MyProtocol) {
    object.method1()
    object.method2()
}
In the example above, we've created a function named `performAction` which takes an object that conforms to `MyProtocol`. The function calls the `method1` and `method2` methods on the object.

Conclusion

Protocols in Swift are a powerful tool for defining and enforcing requirements for classes, structs, and enums. By using protocols as types, we can create flexible and reusable code that can work with any object that conforms to a specific protocol.