1. 程式人生 > >The beauty of Protocol Oriented Language -Swift

The beauty of Protocol Oriented Language -Swift

The beauty of Protocol Oriented Language -Swift

Most of us must be aware of what Protocols and Extensions mean in swift, and how they have been used traditionally. The protocol sets a rule to implement the methods that have been defined within the protocol. And the extension provides the privilege to add more functionalities to the class, struct etc.

Apart from this, we can use protocols and extensions for better code reusability, code readability and obviously to maintain clean code.

Present View Controller code set up in Extended Protocol

Consider an example, you need to show InformationViewController in many places of the application. Generally, you add this code probably for a button clicks -

Everywhere you need to have this code for presenting InformationViewController across different ViewControllers. It is a high time to think for a better way to reuse the code.

In the above code, we see InformationViewDelegate protocol which could have methods like,

As we know in swift, protocols can be extended. Similarly InformationViewDelegate

can also be extended to show InformationViewController.

Now everywhere when you need to present InformationViewController, you can call an extended protocol method. Like,

presentInformationViewController() a method is defined at only one place. This helps to call the extended protocol method from any view controller that wants to present InformationViewController over it. Isn't it simple?

Likewise, you can use this technique to show loading animation view which usually appears in most of the screens in the applications, downloading UI, Share UI and many more.