Protocol Extensions to avoid code duplication

UIViewController and UITableViewController both have a lot in common but unfortunately we cannot have single place to write the code using inheritance. Thats a shame!Available approaches:

  1. Subclass a new View controller and implement table in it to make your own TableViewController.

This approach is by far sensible available option out there apart from that you are reinventing the wheel.

2. Write a UIViewController category extending the functionality..
Now every view controller in you class has these extended functionality, what if a set of view controllers doesn’t require this functionality unfortunately there is no way around it.

3. Write a method in you BaseViewController and duplicate it in BaseTableViewController
Yeah, the word duplicate says it all. So I used protocol extensions to find a nice way to solve this problem.

Protocol extensions are the best way to solve this problem,
Create a protocol extension and implement the common functions and confirm your view controllers to that protocol.
Now all your common functions logic is inside protocol extension where the Self is UiViewController.


It is obvious that we duplicated the code. This can be avoided using protocol extensions

After using protocol extensions:

There you go one more reason to embrace swift! 🙂

Leave a Reply