What are Swift Protocols?

The term “protocol” can be confusing to a new swift programmer but it is really all very simple. How Apple defines a protocol, “A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.”

Remember that a swift class has different properties and functions. (The same way a Java class has instance variables and methods) Sometimes we would like to make sure that our classes have specific characteristics and can perform specific tasks, thats where protocols come in. Let me explain.

Lets say we create a protocol for a dog:

protocol Dog {

    func bark()

    func eat()

    func sleep()

}

You can see that a protocol looks very similar to a class. The functions bark(), eat() and sleep() are defined. However unlike a class, the protocol’s methods have no body.

Swift classes can “conform” to protocols. What this means is that if a class chooses to conform to a protocol then it must implement all of the methods defined in the protocol.

If I were to create a class that I would like to “conform” to my protocol that I named “Dog”, the code would look like the following.

class Pug: Dog {

}

You see that in order for a class to conform to a protocol, you need to add the :Dog after the class name, where Dog is the protocol name. This lets swift know that the class “Pug” will conform to the protocol “Dog”.

Now this code will not actually compile. Remember I mentioned that any class that “conforms” to a protocol must implement all of the protocol’s methods? Well thats the case here. In order for our pug class to properly conform, we need to add all the methods that the protocol “Dog” requires.

This is what a proper “Dog” protocol conformity  looks like.

class Pug: Dog {

    func bark() {

        print(“BARK!”)

    }    

    func eat() {

        print(“CRUNCH CRUNCH CRUNCH”)

    }

    func sleep() {

        print(“SNOREEEEEEE”)

    }

}

You see that all of the methods from the protocol are added to our class. This means that we have properly made our pug a dog!

1 Comment

  1. […] A delegate in swift is simply an object that conforms to a Protocol (My blog post explaining Protocols). […]

Comments are closed.