Optional Protocols in Swift
All functions in a protocol are required by default, which means if you create and use a protocol, you have to provide the implementation for every method that is declared in your protocol.
Let’s say you create a protocol “Properties”, with the following three methods :
and if you want to implement your “Properties” protocol, you have to provide the implementation for all three functions.
And if we don’t provide it, compiler will start giving that annoying error:-
So, there are two ways to resolve this :
- Optional Protocol
In your protocol add optional to those methods which you don’t need to implement. And along with that, you have to add @objc in the protocol and before the optional keyword.
Now we are good to go and no longer required to provide the implementation for the optional method.
One limitation with optional protocol is that you cannot use it with struct(value type) as you are using @objc.
2. Protocol Extension
Another way is to create an extension of the protocol and provide a default implementation of that method. Like the following example:-
And that’s it, add all those methods that are not required in the extension body with default implementation and we are done…