Protocols in Swift are similar to interfaces in other programming languages. They are essentially sets of rules that a class or struct can adopt, allowing them to conform to the protocol’s requirements. Protocols help us write more modular and reusable code, as they establish a declarative way of interfacing with objects.
A protocol can be seen as a contract between different entities in a codebase. In a protocol definition, we define the required properties and methods that a conforming type should have. For example, let’s declare a protocol that represents a simple car:
protocol Car {
var color: String { get }
var speed: Double { get }
func startEngine()
func stopEngine()
}
In the above example, we declare a protocol called 'Car.' The 'Car' protocol requires any type conforming to it to have two properties called 'color' and 'speed,' which are both read-only. Additionally, any conforming type should have two methods for starting and stopping the engine.
To conform a class or struct to a protocol, we simply need to declare that the type adopts the protocol. For example:
struct SportCar: Car {
let color = "red"
let speed = 100.0
func startEngine() {
print("Starting engine...")
}
func stopEngine() {
print("Stopping engine...")
}
}
The above example shows a 'SportCar' struct that conforms to the 'Car' protocol. It has both color and speed properties, as well as startEngine and stopEngine methods. Notice that when we adopt the 'Car' protocol, we are required to implement all the properties and methods defined in the protocol.
One of the main benefits of protocols is that they allow us to write code in terms of what it does, rather than what it is. This means that we can define functions that take in any type that conforms to a given protocol. For example:
func race(car: Car) {
print("Ready, set, go!")
car.startEngine()
// do some racing
car.stopEngine()
}
The 'race' function takes any parameter that conforms to the 'Car' protocol, meaning that it could take an instance of the 'SportCar' struct that we defined earlier. We can now reuse this method on any other types that also conform to the 'Car' protocol.
Protocols are an integral part of Swift programming, and they are an invaluable tool when it comes to writing reusable and modular code. They help you define a declarative way of interfacing with objects, making your code more expressive and readable. By defining protocols and using them in your code, you can ensure that your code is loosely coupled, which means that you can make changes to different parts of your codebase without affecting other parts.