Swift | Advanced Protocols in Swift

Conforming protocols to extensions,Protocol Inheritance,Class Only Protocols, and Adding Extensions To Protocols

Che Rin (Elizabeth) Yu
Geek Culture
2 min readFeb 10, 2022

--

Photo by Sven Mieke on Unsplash

Conforming protocols to extensions.

Extensions can conform to protocols.

For example, Strings are structures. You can extend the functionalities of strings by conforming them with a protocol of your own. In this example, I used the name property as a conforming type to the Person protocol. Then I implemented the functionalities of the person protocol inside of the String strucuture by using the extension keyword.

Protocol Inheritance

A protocol can inherit more than one protocol and add more requirements than those of the existing protocol.

The protocol superCalculator conforms to another protocol called calculator. Therefore because myClaculator( ) class conforms to superCalculator, which conforms to calculator( ), we need to implement properties and methods from both protocols.

Protocols can also inherit multiple protocols like the example below.

The ReadWriteSpeakable protocol conforms to the Readable and Writeable protocol so when we implement a class/struct/or enum that conforms to the ReadWriteSpeakable protocol we need to implement all methods from all three protocols.

Class Only Protocols

By adding the class keyword to the protocol’s inheritence list, you can restrict the protocol to be adopted only for class types, To restrict to class only protocols, place the class keyword at the beginning of the protocol’s inheritance list.

As you can see fullCalculator inherits class, which is a classOnly protocol. This means that only classes can conform to the protocol.

Adding Extensions To Protocols

You cannot implement functionalities to protocols but you can do so by extending them. When you extend a protocol, and as you add the functionalities, you do not have to redefine them in your structs/classes/ or enums.

In the example above we have a protocol called add. The structure addingCalc() conforms to the add protocol so it has to implement its functionalities. The function printAdd() is an extension to the add protocol and since it is an extension, it can be implemented. This means that we do not have to implement printAdd() in the structure, and we can call it right away.

--

--