Define Protocols in Swift
Written by Team Kodeco
Protocols in Swift are a way to define a blueprint of methods, properties and other requirements that a class, struct, or enum must implement.
They allow you to define a common interface for different types of objects, making it easy to work with objects that have different implementations.
Here’s an example of how to define a protocol in Swift:
protocol Driveable {
var speed: Double { get set }
func start()
func stop()
}
This defines a protocol called Driveable
that requires any type that adopts it to have a property called speed
(that is gettable and settable) and two methods called start()
and stop()
.
You can now create a struct or a class that conforms to this protocol by implementing the required properties and methods:
struct Car: Driveable {
var speed: Double
func start() {
print("Car started")
}
func stop() {
print("Car stopped")
}
}
This creates a struct called Car
that conforms to the Driveable
protocol and has a property speed
and methods start()
and stop()
.
You can now use the Car
struct as a Driveable
object like this:
func startDrivable(drivable: Driveable) {
drivable.start()
}
startDrivable(drivable: Car(speed: 0)) // prints "Car started"
Defining Static Functions and Properties in Protocols
Static functions and properties can also be defined within protocols in Swift. This allows for reusable code and shared data to be shared across all types that conform to the protocol.
To define a static function in a protocol, you use the static keyword followed by the function declaration. For example:
protocol Driveable {
static func calculateFuelEfficiency(fuel: Double, distance: Double) -> Double
static var topSpeed: Double { get }
}
struct SportsCar: Driveable {
static func calculateFuelEfficiency(fuel: Double, distance: Double) -> Double {
return distance / fuel
}
static var topSpeed: Double {
return 150
}
}
struct Sedan: Driveable {
static func calculateFuelEfficiency(fuel: Double, distance: Double) -> Double {
return distance / fuel
}
static var topSpeed: Double {
return 120
}
}
let sportsCarFuelEfficiency = SportsCar.calculateFuelEfficiency(fuel: 50, distance: 500)
print(sportsCarFuelEfficiency) // 10.0
let sedanFuelEfficiency = Sedan.calculateFuelEfficiency(fuel: 40, distance: 400)
print(sedanFuelEfficiency) // 10.0
print(SportsCar.topSpeed) // 150
print(Sedan.topSpeed) // 120
Conforming to Multiple Protocols in the Same Class
It’s possible to use multiple protocols in the same class, struct or enum.
protocol Paintable {
func paint(color: String)
}
class Truck: Driveable, Paintable {
var speed: Double = 0
func start() {
print("Truck started")
}
func stop() {
print("Truck stopped")
}
func paint(color: String) {
print("Truck painted with color: \(color)")
}
}
In this example, the Truck
class conforms to both Driveable
and Paintable
protocols and it has to implement all the required methods and properties from both protocols.