Introduction
A protocol is a set of methods, attributes, and other customized specifications for a certain task or piece of functionality. A class, structure, or enumeration can then adopt the protocol to offer an actual implementation of those requirements. Any type that meets the protocol's requirements is said to conform to that protocol.
In simple words, A protocol is a set of methods or attributes that classes can use to operate (or any other types).
To define a protocol, we require the protocol keyword.
protocol GreetMessage {
// this is called the blueprint of a property
var name: String { get }
// this is the blueprint of a method
func text_message()
}
Here,
GreetMessage - name of the protocol
name - a gettable property
text_message() - method definition without any implementation
Syntax:
protocol SomeProtocolName {
// protocol definition here
}
Conform Class To Swift Protocol
To use a protocol in Swift, other classes must conform it. We must give a real implementation of the method when we conform a class to the protocol.
Here's how to make a class conform to the protocol:
// conform class to get the Greet protocol
class Employee: GreetMessage {
// implementation of the property
var name = "Perry"
// implementation of the method
func text_message() {
print("Hello, Good Morning!")
}
}
Here, we've made the Employee class conform with the Greet protocol. As a result, we must implement the name property and the message() method.
Let’s look at the example of swift protocol,
Swift Protocol To Calculate Area
protocol Quadilateral {
func getArea(length: Int, breadth: Int)
}
// conform to the Quadrilateral protocol here
class Rectangle: Quadrilateral {
// implementation of the method
func getArea(length: Int, breadth: Int) {
print("Area of the rectangle:", length * breadth)
}
}
// creating an object
var r1 = Rectangle()
r1.getArea(length:4, breadth: 7)
Output
Area of the rectangle: 28
In the above example, we implemented the Quadrilateral protocol. The protocol comprises of the getArea() method's blueprint, which has two parameters: length and breadth.
The rectangle is a Quadrilateral-based class that provides the actual implementation of the getArea() method.