What is 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.

Example :

Protocols are a good way to define a set of required functionality that other types can adopt.  Protocols provide information about what a type can do, not necessarily what it is. Classes and structs provide you with information about what an object is, but protocols provide you with information about what an object does.

 protocol Sound {
    func makeSound() 
}

Great. We defined a protocol, Sound, that specifies that something must have a makeSound()function. It doesn’t matter what the object really is, because we only care about whether or not it meets our requirements for the Sound protocol. Let’s see how this works in practice:

struct Dog: Sound {
    func makeSound() {
        print("Woof")
    }
}
 
struct Tree: Sound {
    func makeSound() {
        print("Susurrate")
    }
}
 
struct iPhone: Sound {
    func makeSound() {
        print("Ring")
    }
}

Protocol Extension :

We can extend classes and structs in Swift to add functionality to them. However, with protocols, extensions are even more powerful, because they allow you to provide default functionality for your protocols. What this means is that you can declare protocols with requirements that are automatically fulfilled.

Basically, protocol extensions allow you to retain one of the best features of subclassing (inheritance) while gaining all of the best features of protocols. Let’s go back to our animals again!

Imagine that we’re in a new world where each and every animal makes its own respective sound (like woof, meow, moo, etc.) but they all make a universal sound. We’ll call this universal sound “Wow”. We can now create an extension to our Sound protocol:

extension Sound {
    func makeSound() {
        print("Wow")
    }
}

now we will create new animal Cat

struct Cat: Sound {
}

we don’t need to confirm protocol method

var cat = Cat()
cat.makeSound()   //will print "wow"

We can even override default functionality

struct Cat: Sound {
    func makeSound() {
        print("Mawww")
    }
}

240_F_77959340_hWLiOY93juohUoXqjKzqPB79552nw8XU

Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Donate any small amount you think for this knowledge to grow this forum.                        

To Donate –  paypal.me/SandeshSardar

download

Advertisements