Optional Protocol Methods
Swift can be used as both an object-oriented programming language and a protocol-oriented programming language. What is the real difference between the two.
The first and very basic difference I saw with protocol-oriented programming is that we should start with a protocol rather than a super-class.
What is the protocol?
In simple terms, protocol is a kind of interface.
In Objective-C, we have optional keyword to dictate the compulsory and optional methods to the class who gone confirm to this protocol.
It’s compulsory for you to implement required methods and optional’s are not.
In swift can we have optional methods? Many developers say’s ‘NO’ upfront and some of them say’s we have to use @objc keyword in-front of your protocol declaration, which will allow us to use the optional keyword.
@objc protocol NetworkDelegate { @objc optional func onCompletion(data: Data)}
Yes, we can use the @objc keyword and make it available for our Swift code.
Let’s create a class and confirm to the NetworkDelegate.
class APIManager: NetworkDelegate { // No Error}
It will only work with class. As the protocol becomes a class protocol.
Let’s create a struct now and confirm to the NetworkDelegate.
struct APIService: NetworkDelegate { // Error}error: non-class type 'APIService' cannot conform to class protocol 'NetworkDelegate'
Hence, going for @objc is not a good choice.
Apple has said that we should prefer value types over reference types where appropriate.
Means, we should have struct as much as possible. That means we have one more reason to not go for @objc.
Using protocol extensions to create optional protocol methods
However, with Swift 2.0 and onwards it’s possible to define a protocol extension. This allows you to create optional methods for your protocol easily: The protocol extension allows to extend the protocol and have the default implementation for the protocol methods.
protocol NetworkDelegate { func onCompletion(data: Data) func onError(error: Error)}extension NetworkDelegate {func onCompletion(data: Data) { // HAVE A DEFAULT IMPLEMENTATION}func onError(error: Error) { // HAVE A DEFAULT IMPLEMENTATION}}/* Confirm to protocol*/class APIManager: NetworkDelegate { // No Error}struct APIService: NetworkDelegate { // No Error}
You can achieve multiple inheritance as class or struct can confirm to multiple protocols. 😉 😉 😉
Swift tries to fight the inherent OOP problems by introducing a new paradigm called Protocol Oriented Programming. Swift from the very beginning has embraced the idea of value types. Although value types do not support inheritance in Swift, they can conform to protocols which allows them to enjoy the benefits of Protocol Oriented Programming.
If you liked this article, please consider following me on Medium. When I have something new and awesome to share. It’s the best way to find out when I write more articles like this.

