iOS Tutorial [SWIFT] – What Are Protocols?

ios development tutorial protocol

In this iOS tutorial SWIFT protocols, we’re going to show you what protocols are and how to use them through some great examples.

Recommended for you The difference between “!” and “?” in Swift

Definition

Protocol: a blueprint of methods and properties, and can be adopted by classes, structs, and enums.

protocol Location
 
{
 
    var address: String {get set}
 
}
 
struct Person: Location
 
{
 
    var address:String
 
}
 
let Faisal = Person(address:"5 Nutcracker Street")

In the above example, we created a protocol called “Location” that requires an address of type String. We then created a struct called “Person” that conforms to our protocol as notated by the semi-colon.

You might be interested in [SWIFT] Value and Reference Types

Protocols and Delegates

Protocols serve as the backbone for delegates. They do this by saying, “Look. If you want to conform to me, you’ll have to write “x” methods and declare “y” variables.” Just like how we inherit from other classes, we want to use the semi-colon when we want a class, struct, or enum to conform to a protocol.

When comparing different values in swift, we use a variety of protocols that you may have heard of before. They include:

  • Equatable
  • Comparable
  • Printable
Recommended for you Getting Started With Swift 3.0

Variables and Constants

Protocols can also serve as types for a variable or constant for arrays and dictionaries. For example:

protocol Edible
 
{
 
    var nameOfFood:String {get set}
 
    func eat(amtOfFood amtOfFood:Int)
 
}
 
class Food:Edible
 
{
 
    var nameOfFood:String = "Sandwhich"
 
    func eat(amtOfFood amtOfFood: Int)
 
    {
 
      print("We're eating \(amtOfFood) of sandwhiches")
 
    }
 
}
 
func eatTheFood(foodItem:Edible)
 
{
 
    foodItem.eat(amtOfFood: 10)
 
}
 
var newFood = Food()
 
print(eatTheFood(newFood))

It should also be noted that protocols can inhere from each other. When they do, add their requirements on top of each other. You can also try something protocol composition, which is when you make a type adopt multiple protocols at once. Here’s an example:

protocol 

If you liked this iOS tutorial SWIFT protocols, take a look at some of our other stuff at the tutorial section.

Leave a Reply

Your email address will not be published. Required fields are marked *