MobileEntityLogo.png

Hi.

Welcome to the best online resource for IOS & Android tutorials.

Combining protocols to make for more readable code

This is our usual code template for tableviews without using our own protocol combo.


class viewControllerB:UIViewController, UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
    }
}

Now with our new combo protocol our tableView code will look like this


class viewControllerA:UIViewController, table {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
    }
}

Sometimes classes can have so many delegates that it can get confusing. This is just another approach to managing delegates besides extending your classes. What this is good for is creating descriptive delegate names when usually delegate names can be odd depending on the framework that implemented the delegate. Now how do we create the delegate combo, lets take a look.


protocol table: UITableViewDelegate, UITableViewDataSource {}

As you see we created our protocol table and made it inherit from the two delegates used to create a tableView. This is a solution to combine delegates, however you can also add your own methods that the class implementing the table protocol would have to implement. Add your methods to the curly braces at the end of the protocol for example.


protocol table: UITableViewDelegate, UITableViewDataSource {
    func foo()
    func bar()
}

Now our class has to implement foo, and bar methods as well as the tableView methods. Keep in mind that inside protocols function body is not necessary as the function body will be implemented by the class inheriting the protocol. I hope this tutorial helps you clean your code, and is of great use to you.

Top 20 most asked IOS interview questions and answers

Separating vowels from constants in Swift

0