Swift Protocol Conformance with Extensions

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
May 9, 2024
Tutorial: Swift Extensions for Protocol Conformance

Swift Extensions for Protocol Conformance

In Swift, protocol extensions allow you to provide default implementations for methods and properties defined in a protocol. This can be useful when you have a protocol with a large number of methods or properties that can have the same implementation for multiple conforming types.

One common use case for protocol extensions is to extend existing types to conform to a protocol. This can be helpful when you want to add certain functionality to a type without modifying its original implementation. Let's see an example of how to use protocol extensions for protocol conformance:

protocol Vehicle {
    var numberOfWheels: Int { get }
    var color: String { get }
    
    func start()
}

extension Vehicle {
    func start() {
        print("The vehicle starts moving!")
    }
}

struct Car: Vehicle {
    var numberOfWheels: Int
    var color: String
}

struct Bike: Vehicle {
    var numberOfWheels: Int
    var color: String
    
    func start() {
        print("The bike pedals!")
    }
}

let myCar = Car(numberOfWheels: 4, color: "Red")
let myBike = Bike(numberOfWheels: 2, color: "Black")

myCar.start() // Output: The vehicle starts moving!
myBike.start() // Output: The bike pedals!}

In the above code snippet, we have a protocol called Vehicle with two properties (numberOfWheels and color) and a method start. We then provide a default implementation for the start method in a protocol extension. The Car struct and Bike struct both conform to the Vehicle protocol, and the Bike struct overrides the start method with its own implementation.

By using protocol extensions for protocol conformance, we can easily add default implementations for methods and properties, allowing conforming types to benefit from the shared functionality without duplicating code. This can help make your code more efficient and maintainable.