How Swift Protocol replaces Swift Extension?

Protocols are a way of describing what properties and methods something must have, where as Extensions add new functionality to an existing class, structure, enumeration, or protocol type.

Get Started

We’ll discuss here about how we can achieve same functionality by protocols which achieved by extensions. 🧐

Let’s take an example of navigation right bar button. We’ll add right bar button by swift extension & swift protocol. ✍️

Navigation right bar button by Swift Extension

First, we created an extension of UIViewController and added a method “addRightBarButtonByExtenstion” with definition to add right bar button. Also added button target method “rightBarButtonByExtenstionAction” with default empty definition.

Now, use this extension in UIViewController class to add navigation right bar button. We simply, called “addRightBarButtonByExtenstion” method in viewDidLoad life cycle method and it adds bar button. We also override the target method “rightBarButtonByExtenstionAction” here to integrate the tap action.

That’s done! 😉

Navigation right bar button by Swift Protocol

Firstly, we created a swift protocol “ViewControllerProtocols” which have one method declaration “rightBarButtonByProtocolAction”. This method is the target of navigation right bar button.

Now created an extension of protocol “ViewControllerProtocols” which have method “addRightBarButtonByProtocol” with default definition to add navigation right bar button.

This is very simple except one thing. We added objective c attribute @objc before protocol declaration. If you remove this attribute then it gives an error 💀 — “Cannot use ‘rightBarButtonByProtocolAction’ as a selector because protocol ‘ViewControllerProtocols’ is not exposed to Objective-C”

As you know that you have to use @objc attribute in swift before any selector.

Now, let’s use this protocol to add right bar button. We simply, confirm the protocol “ViewControllerProtocols” and call the “addRightBarButtonByProtocol” method in viewDidLoad method to add the button.

Really, this is very easy. Also there is no issue with UIViewControllers’s references regarding retain cycle.

Oh, we achieved ! 👌

Summary

Once you use extension then you have to remember to override target callback method but in case of protocol, you don’t have to remember or override target callback method. Good to follow the protocol oriented programming to setup blueprints for your codebase. Ther are also lots of other benefits of protocols. Loved it! ❤️

Here is link of full source code: https://github.com/sanjeevworkstation/SwiftProtocolReplacesExtension

Thank You. Happy coding! 👍

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store