Protocol — The power of Swift

Part-5 — Protocol as a super-type

Hitendra Solanki
Swift India
2 min readDec 16, 2018

--

Updated on 17th December 2018, 1:34 AM GMT 5:30+

Welcome to the 5th part of this series, In-case you missed previous parts, I will strongly suggest you that first coverup the essential concepts from
Part-1: What is type-casting and class-types?
Part-2 — confirming a protocol
Part-3 — Protocol composition
Part-4 — My rule of thumb for possible data types

Where protocol should be used?

The common use of protocol is for delegate and datasources.
Example is UITableDelegate and UITableViewDatasource.

UITableDelegate, UITableViewDatasource both are protocols. You can also create your custom protocols to pass and retrieve data from one ViewController to other ViewController. This is knows as delegation pattern(we will cover this later at right time).

Wait please, why Apple Created two different protocols for the UITableView?
-
Apple created two different protocol to just divide the responsibilities
- UITableViewDelegate only handles the UI and user interactions related methods like ‘didSelectedRow:atIndexPath:’
- UITableViewDatasource only handles the methods that provides the data to tableview like ‘cellForRow:atIndexPath:’

Another use of protocol is to define common datatype for multiple types when you are performing the common operations on those different datatypes.

Protocol as a super-type example 1

in above example,
we have protocol named InformationDisplayble, and two classes named Employee and Student. Both classes confirms the protocol in separate extension.

If you remember my rule of thumb for possible data-types, both the classes will have 3 possible data-types.

Data-types of Employee class will be Employee, InformationDisplayable and AnyObject.
Data-types of Student class will be Student, InformationDisplayable and AnyObject.

We have two common data-types for both classes, which are InformationDisplayable and AnyObject.

We have one function named displayInformation() which accepts one argument of type InformationDisplayable. we are calling the method object.displayInformation() inside this function. The prototype of method displayInformation() is written inside the protocol declaration, so we are allowed to call this method on the InformationDisplayable type instances.

This is how we can use the protocol as a super type and write clean and common code with the help of protocol and remove code redundancy. In above example our displayInformation() is reusable for objects of all the classes which confirms the protocol InformationDisplayble.

I have question, time please

Intelligent question, stay tuned for the answer

More content coming soon…
Stay tuned, @hitendra.hckr is typing

--

--

Hitendra Solanki
Swift India

Software Engineer, {Self-taught Developer by passion, Quick Learner, Mentor, blogger, TeamLead} GitHub: https://github.com/hitendradeveloper