Declaring and adopting Protocols in Swift

Ashley Oldham
3 min readJun 15, 2021
laptop displaying code

As defined by the swift docs, a protocol is a blueprint of methods, properties and other requirements that suit a particular task or piece of functionality. Protocols can be adopted by a class, structure and enumeration. Basically, a Protocol is a set of predefined rules that can be passed onto classes, structs and enums to follow.

Defining a protocol

We define a protocol in a similar way to what we have seen before when defining a class or other types. We use a keyword to indicate what we are defining. In this case, ‘protocol’ followed by a name using upper CamelCase.

definition of Protocol
Syntax of a protocol

Adopting a protocol

We adopt a protocol by inserting the name after the type, separated by a colon. If we are inheriting from a superClass, then we name the superClass first, then the protocol. We can also adopt multiple protocols and this is done with the separation of a comma.

syntax of class adopting a protocol
How to adopt protocol
syntax of adopting multiple protocols
How to adopt multiple protocols

Conforming to protocol

If a protocol is being adopted by a class or other custom type, then it must also contain the methods or properties that are part of that protocol. You will receive an error if the type does not conform to the adopted protocol.

Error produced when class does not conform to protocol
Error when not conforming to protocol.

Protocols are particularly useful when you require a class (other types are available!) to include certain properties or methods. When a type adopts a Protocol, they must implement their requirements. An example of this could be a gym holding information of it’s members, and need to ensure the correct data is logged each time a new member is added. By creating a MemberProtocol which dictates the required properties, the class must also implement these requirements when adopting the MemberProtocol.

NB: When declaring properties within a protocol, you must explicitly define each property with either { get } or both { get set }. With regards to functions, these are declared as part of the protocol’s definition, but are not written with a function body. Parameters can be defined here also, but not default values. This will be defined within the class, enum or struct where the protocol is used.

Example of protocol
Example use of protocol
class adopting protocol
class adopting a protocol

For a more in-depth look at protocols, you can find lots of examples in the swift docs.

--

--

Ashley Oldham

Career changer but still a problem solver. New to Code and blogging my experiences with it. Hoping this helps both you and I learn!