All Articles

What are protocols (Swift)?

There are a few ways of being notified when the orientation of your iOS device has changed.

What are protocols?

According to Apple’s documentation, protocols are:

“A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said toconform to that protocol.”

I understand it this way: a protocol is a set of standards or rules (methods, properties) by which another class has to conform to, in order to implement that that protocol. It is akin to a blueprint or a framework. Let’s look at an example below.

protocol humanProtocol {
    func breathe()
    func eat()
}

class Person: humanProtocol {

    func breathe() {
        print("Taking a breath!")
    }

    func eat() {
        print("Eating...")
    }

In this example, the class Person conforms to the humanProtocol (because I assume most if not all humans breathe and eat). If you leave out the functions breathe() and eat(), the compiler will give you an error saying that the Person class does not conform to the humanProtocol.

Why does a class need to conform to a protocol?

In our example above, a person cannot survive without breathing or eating. Thus, the person would not exist without those functions.

Similarly, a tableView in iOS cannot show its data or perform correctly unless it implements the following protocols. We can’t have a tableView without knowing how many sections there are, how many rows there are, and displaying the cells of our table.

//Required method 1
func numberOfSectionsInTableView(tableView: UITableView) -> Int

//Required method 2
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

//Required method 3
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell