Writing Your First Protocol

To create a protocol, you start with the keyword protocol and then give it a name, followed by a pair of curly brackets. A basic protocol would look like this:

protocol MyProtocol {}

You might notice that this newly created protocol is completely empty. Although it is empty, it is valid. The protocol doesn’t currently have any functions that it wants you to conform to, but you can provide an implementation of it already. You’ll create a class that conforms to MyProtocol. It won’t be hard to conform to it because it doesn’t have any functions to conform to yet. It’s like if someone gave me a blank shopping list: I would drive to the supermarket and, when I got there, I would just turn around, because there is nothing ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.