An Advanced Swift Feature: Protocols

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

by The Captain

on
April 15, 2023

An Advanced Swift Feature: Protocols

In Swift, protocols are a powerful feature that enable you to define a blueprint of methods, properties, and other requirements that a particular class or struct should adhere to. Protocols allow you to define a flexible and scalable architecture in your code that is easy to understand and maintain.

Defining a Protocol

Let's try to define a simple protocol Animal with properties name and category, along with a function makeSound:

protocol Animal {
    var name: String { get set }
    var category: String { get }
    
    func makeSound()
}

Here, we've defined two properties (name and category) using { get set } and { get } keywords respectively. The makeSound function is not implementing anything at this point, but it requires any conforming class or struct to implement this function.

Implementing a Protocol

Let's create a class Dog that conforms to the Animal protocol we just defined:

class Dog: Animal {
    var name: String
    var category: String
    
    init(name: String) {
        self.name = name
        self.category = "Domestic animal"
    }
    
    func makeSound() {
        print("Bark!")
    }
}

Here, we've implemented the Animal protocol using the class Dog and provided the required property and function within its body. Note that the class Dog must implement all the properties and functions declared in the protocol.

Using a Protocol

Now that we have a protocol and a class that conforms to it, let's try to use it:

func describe(animal: Animal) {
    print("I have a \(animal.category) named \(animal.name)")
    animal.makeSound()
}

let myDog = Dog(name: "Buddy")
describe(animal: myDog)}

Here, we've defined a function describe that takes an Animal as a parameter and prints out its category and name. We've created an instance of the Dog class and passed it to the describe function to print out the required information.

Conclusion

So, this is how protocols work in Swift. They provide a way to define a set of requirements that any class or struct can conform to. They also help in defining a flexible and scalable architecture for your codebase, which is easy to understand and maintain.