Swift 3: Protocol Part 1



Introduction:


Protocol main and widely used concept in objective c and swift both. So here we will be discussing in swift. We have two parts for a protocol. Part -1, will have basic terminology and concept to understand it and Part 2 and Part 3 will have some more drills in detail about it.

The protocol you can think of “Contract” between two bodies. If anyone has acquired it then, that has to follow certain rules to incorporate the action of the contract. Same way Protocol in objective will act in the same way.

Protocols define the set of methods, properties, and required pieces of functionality. Any type whoever going to conform it will have to conform first and then implement the requirement. The protocol can be adopted by a class, struct, enum. Any type that fulfilling the requirement of that protocol is said to conform to that protocol.


If you conform to the protocol then we need to implement the requirement. We can extend the protocol as well to extend the functionality of any type mentioned above.

We will learn the following things:
  • Syntax
  • How to adopt or conform a protocol?
  • How to create delegate property of protocol?
  • How to call the method using delegate property?
  • Implement the protocol method in the conforming class.


Syntax:


protocol myProtocol {

    // protocol definition

}


Adopting or conforming Protocol(s):

1) conforming one protocol at a time 


class Car: myProtocol {

    func customMethod()

}


2) conforming multiple protocols 

You can adopt a protocol after placing protocol’s name after the custom type and after the: (semicolon).


class Car: Protocol1,Protocol2,Protocol3 {

    

}


NOTE:
If a Certain type has the super class then after: super class must come and then after that protocols name separated by the comma. The compiler will error if you try to place the super class name after the protocol name, “SuperClass” must appear first in the inheritance clause.


class Car: CarBaseClass, Protocol1,Protocol2,Protocol3 {

    

}


As CarBaseClass is the super class of Car class.

Delegate Property:




class Car: myProtocol {


    var delegate:myProtocol?

}



Calling Method using delegate:

For this method, you need to call from another source.
delegate?.customMethod() // ? will make sure if delegate is then next thing will not be executed.

Implement Protocol method:




class Car: myProtocol  {


    func customMethod() {

    }

}



That’s all from the basics of Protocol. I will come with some more drill-down details of Protocol in Part - 2. Warm welcome for your suggestions to make this blog clearer.

Wrapping Up: 

As you have learned about the basics of the protocol.  We will continue with the next part of it stay tuned for next. blog.

Happy Coding 😊




Comments

Popular posts from this blog

Copy Vs Mutable Copy in iOS

How to Disable iOS/iPad App availability on Mac Store, Silicon?

Closures in Swift - Part 1