Swift Protocols

Swift Protocols

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task.

It is essentially a "contract" that any class, struct, or enum can choose to adopt.

If a type adopts a protocol, it guarantees that it provides the specific features demanded by that protocol.


Defining a Protocol

You define a protocol using the protocol keyword.

Inside the protocol, you list the property and method signatures, but you do not provide the actual code body.

Defining a Protocol:

protocol Drivable {
    var topSpeed: Int { get }
    func drive()
}

Notice that the drive() method has no curly braces {}. It just defines the requirement!


Adopting a Protocol

To make a class, struct, or enum adopt a protocol, you write the protocol name after the type's name, separated by a colon.

Once adopted, you must implement all the required properties and methods.

Conforming to a Protocol:

protocol Drivable {
    var topSpeed: Int { get }
    func drive()
}
struct Car: Drivable {
    var topSpeed: Int = 120
    func drive() {
        print("Driving at \(topSpeed) mph!")
    }
}

let myCar = Car() myCar.drive()


Multiple Protocol Adoption

Unlike class inheritance, where you can only inherit from a single superclass, a type can adopt multiple protocols at the same time!

You simply list them, separated by commas.

Multiple Protocols:

protocol Identifiable {
    var id: String { get }
}

protocol Purchasable { var price: Double { get } }

// Struct adopting two protocols struct Product: Identifiable, Purchasable { var id: String var price: Double }


Protocols as Types

You can use protocols as types, just like Int or String. You can create arrays of a protocol type, or use them as function parameters!


Exercise

Can a Swift struct conform to multiple protocols at the same time?