Protocols in Swift are very powerful constructs to define a list of methods for a specific task or functionality that classes or structures should implement. The protocol provides a blueprint of methods or properties that a class or structure must implement to conform to that protocol. Conforming to a protocol means providing an implementation for all the methods or properties declared in the protocol.
To implement a protocol in Swift, you can declare and define it using the keyword protocol. Inside the protocol, you can declare methods and properties that should be implemented by the classes or structures conforming to the protocol. Here is an example:
protocol CanFly {
var airspeedVelocity: Double { get }
func fly()
}
class Bird: CanFly {
var airspeedVelocity = 10.0
func fly() {
print("The bird is flying at a speed of \(airspeedVelocity) km/h.")
}
}
In the example above, we defined a protocol named CanFly with a property airspeedVelocity of type double and a method fly(). We also created a class named Bird that conforms to the CanFly protocol by implementing the protocol’s airspeedVelocity property and fly() method.
If a class or structure doesn't implement all the methods and properties declared in the protocol, it won't conform to it, and the compiler will generate an error at compile time. In the example below, the Plane class has implemented the CanFly protocol's airspeedVelocity property, but it fails to implement the fly() method, resulting in a compile-time error.
class Plane:CanFly {
var airspeedVelocity = 900.0
}
A class or structure can conform to multiple protocols by listing them after the colon, separated by commas, as shown in the example below:
protocol CanSwim {
var waterSpeed: Double { get }
func swim()
}
class Duck: CanFly, CanSwim {
var airspeedVelocity = 20.0
var waterSpeed = 10.0
func fly() {
print("The duck is flying at a speed of \(airspeedVelocity) km/h.")
}
func swim() {
print("The duck is swimming at a speed of \(waterSpeed) km/h.")
}
}
In the example above, we defined another protocol named CanSwim with a property waterSpeed of type Double and a method swim(). We then created a class named Duck that conforms to both the CanFly and CanSwim protocols. The class provides implementations for all the methods and properties declared in the two protocols.
Swift protocols are a powerful way to define a list of methods and properties that should be implemented by the classes or structures. It makes the code more modular and clean. This tutorial demonstrated how to define and implement Swift protocols by using examples. Understanding protocols is essential to become a good Swift developer.