Skip to main content

Swift Protocols

Protocols is set of user defined rules which are used to implement methods and properties and add new features. This mechanism is useful to handle complex structure in easy and effective manner. In every protocols can be grouping of more than one properties and methods that is depends upon development situation. But they are cannot implement definition of methods. We can declare protocol in using of this syntax.

protocol SomeName {
    // protocol definition
}

Define of protocol by using of protocol keyword, After that mention the name of protocol. body of protocol is defined by curly braces. and inside the body are defining there set of rules and method.

Protocol is adopts by structure, class and enumeration type. And those are define the properties of protocol.

Protocol adopted by enumeration

//Declare protocol
protocol setRules{
    //Method of protocals
    func getValues()->String
}

//Adopt the properties of protocols
enum Student : setRules{

    case RecordOne
    case RecordTwo
    //Define protocol method definition
    func getValues() -> String {
        
        return "Student Records "
    }
    
}

let record : Student = Student.RecordOne
let info = record.getValues()
print(info)

Output

Student Records

Note that this is very basic example to use protocol in enum data type. In this example protocol is declared getValue() method and their definition are implemented by inside enum. Now use this protocol on structure data type.

Protocol adopted by structure

//Declare protocol
protocol setRules{
    //Method of protocals
    func getValues()->String
}

//Adopt the properties of setRules protocol
struct Student : setRules{

    var info : String = "Student Records Structure"

    //Define protocol method definition
    func getValues() -> String {
        
        return info
    }
    
}

let record : Student = Student()
let info = record.getValues()
print(info)

Output

Student Records Structure

Note that both mechanism structure and enumeration adopted protocol. And this are define the properties of protocol.

Protocol adopted by class

//Declare protocol
protocol setRules{
    //Method of protocals
    func getValues()->String
}

//Adopt the properties of setRules protocol
class Student : setRules{

    var info : String
    init(info:String){
        self.info = info
    }

    //Define protocol method definition
    func getValues() -> String {
        
        return info
    }
    
}
let record : Student = Student(info:"Student Class")
let info = record.getValues()
print(info)

Output

Student Class

In Above all example goal is you are familiar with how to use protocols in class, structures and enumeration data type. You can observe that protocol properties are defined all example in similar ways.

In this situation question are occurred in your mind Can there are possible to inherit one protocol by another protocol. The answers is yes we can do this process.

Inheriting one protocol to another

That is special concept, When we define two protocols like SetRules and GetRules. and GetRules are adopted by SetRules and SetRules are adopted by other class, structure and enumeration. Then in this situation adopted class are responsible to define both protocols properties. For example.

//Declare protocol
protocol GetRules{
    //Method of protocal
}
//inherit GetRules properties
protocol SetRules : GetRules{
    //Method of this protocal
}

//Adopted the SetRules protocol
class Student : SetRules{

}

Think about this situation, Here Student class directly not use protocol GetRules but internally SetRule are adopted their properties. So Student class are working the definition of both protocols. See this example.

//Declare protocol
protocol GetRules{
    //Method of protocal
    func getValues()->String
}
//inherit GetRules properties
protocol SetRules : GetRules{
    //Method of this protocal
    func setValues(_:String)
}
//Adopt the properties of SetRules protocol
class Student : SetRules{

    var info : String

    init(info:String){
        self.info = info
    }
    //Define SetRules protocol method 
    func setValues(_ newInfo:String){
        
        self.info = newInfo
    }
    //Define GetRules protocol method 
    func getValues() -> String {
        
        return info
    }
    
}

let record : Student = Student(info:"Old Student Class")
var info = record.getValues()

print(info)

record.setValues("New Student Class")

info = record.getValues()
print(info)

Output

Old Student Class
New Student Class

Note that in above program it will work without defining of getValues() method, but when we are create a instance of class then compiler are produce an error. Because when creating a object of class there are required to define of all methods to adopted class.

In a case, When both protocol are exist same signature method then don't need to define both method in inherited class implementation.

protocol LowSpeed{
    func runningStatus()->Bool

    func minimumSpeed()->Int
}
protocol HeighSpeed:LowSpeed{
    func runningStatus()->Bool //same method
    func maximumSpeed()->Int
}
class MyCar : HeighSpeed{
   //Define class propeties
    var status : Bool 
    var minSpeed : Int
    var maxSpeed : Int  

    init(minSpeed : Int ,maxSpeed : Int, status : Bool ){
        self.status=status
        self.minSpeed=minSpeed
        self.maxSpeed=maxSpeed

    } 
    func runningStatus() -> Bool{
        return self.status
    }
    func maximumSpeed() -> Int {
        return self.maxSpeed
    }
    func minimumSpeed() -> Int{
        return self.minSpeed
    }
}
let myCar : MyCar = MyCar(minSpeed:30,maxSpeed:230,status:true)

print("Running Status : \(myCar.runningStatus())")
print("Minimum Speed  : \(myCar.minimumSpeed())")
print("Maximum Speed  : \(myCar.maximumSpeed())")

Output

Running Status : true
Minimum Speed  : 30
Maximum Speed  : 230

When in special case protocol are work only classes and structure are enumeration are not invoke protocols then we can define protocol that are specially targeted to class.

//protocol rules for Classes
protocol ClassRules:class{
    
    func getClassName() -> String
}
//Okay that are work
class MyClass : ClassRules{
    func getClassName() -> String{

        return "MyClass"
    }
}

This example protocol are targeting to classes that is not indicates which classes that are using protocales rule. But in declaration of protocal there are indication of it will work on only class.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment