Protocols in Swift

Apple’s definition of Protocol

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 to conform to that protocol.

In plain english, protocol is just a set of requirements or rules that you have set for your class, structure, or enumeration. Any types that conform to a protocol must include the required properties and functions in order to satisfy the requirements. Using protocol will provide a safety check to ensure the integrity of your data structure.

Syntax

protocol example {
//Definition goes here
}

Syntax of protocol is fairly simple. You would implement it the same way you approach a class or structure.

Protocol Examples

protocol Person {
  var name: String {get}
var age: String {get}
var hairColor: String {get set}
}

Here we have a protocol called Person with three stored properties, and they are name, age, and hair color. Any class, structure, or enumeration that adopts this protocol must include these three properties. Each property must state whether the variable is a gettable or settable. It is important to note that properties must be defined using var , any attempts of declaring it a constant will throw an error.

protocol Person {
  var name: String {get}
var age: String {get}
var hairColor: String {get set}
  func walk()
func run()
func eat()
}

A protocol is not only limited to defining stored properties, but we can implement functions as well.

Should I use Protocols?

My answer is “absolutely”. Protocol is a very useful tool, and one of biggest benefit is that it provides a safety check for your code. Protocol is like a personal assistant that reminds you that a certain class, structure, or enumeration must have certain attributes before it’s declaration. This is helpful when you want to create multiple objects that are slightly different, but still derive from the same standard design. For example, imagine you want to create a object that is of person. This person can be a baby, young child, and adult. Baby can not walk or run, young child can go to school, adult can go to work, as you see we can still use the object of person, but we can set different protocols for each person depending on their age.

Protocols are used in many functions, even though you might not have realized it. Table view delegate and data source are one example of protocol. In order to properly implement table view, we must declare our delegate and data source.


Thanks for tuning in 😎!

Like what you read? Give Henry Chan a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.