Thuta Learning
AdvancedProgrammingbeginner

Protocols

Relax. We'll talk through this in plain words — no textbook voice.

Protocol is a contract that says what properties/methods a class, struct, or enum must have. Protocol-oriented programming is used heavily in Swift development.

Using protocols lets you write code based on behavior instead of being tied to one concrete type. They're extremely useful for testing, dependency injection, and reusable components.

swift
protocol Payable {
    var amount: Double { get }
    func pay()
}

struct CreditCardPayment: Payable {
    let amount: Double

    func pay() {
        print("Paid $\(amount) with credit card")
    }
}

let payment = CreditCardPayment(amount: 29.99)
payment.pay()

Payable protocol requires an amount property and a pay() method. CreditCardPayment struct follows that contract.

You should see
Paid $29.99 with credit card

Easy traps

  • If you miss writing one of the methods/properties a protocol requires, the type won't conform and you'll get a compile error.
Protocols | Thuta Learning