Vamsi Anguluru

iOS Engineer

Swift Engineer

Games Developer

Vamsi Anguluru

iOS Engineer

Swift Engineer

Games Developer

Blog Post

Protocol Extensions To Avoid Code Duplication

April 26, 2016 Uncategorized

Problem:
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.

Solution:
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.

Before:

class BaseViewController: UIViewController {
    func configureView() {
        self.view.backgroundColor = UIColor.redColor()
    }
}
class BaseTableViewController: UITableViewController {
    func configureView() {
        self.view.backgroundColor = UIColor.redColor()
    }
}

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

After using protocol extensions:

protocol SkinnableController {
}

extension SkinnableController where Self: UIViewController {
    func configureView() {
        self.view.backgroundColor = UIColor.redColor()
    }
}

//Now both table and view controllers can implement this protocol and gain the functionality of accessing this method.

class BaseViewController: UIViewController, SkinnableController {
    //can access configureView() 
}
class BaseTableViewController: UITableViewController, SkinnableController {
    //can access configureView() 
}

There you go one more reason to embrace swift! 🙂

Write a comment