Protocols & Extensions

A protocol defines a set of requirements — methods and properties a type promises to implement — without providing any implementation itself. Combined with extensions, which let you add functionality to a type after it's already defined (even a type you don't own, like Swift's own Int), this is how Swift shares behavior across unrelated types without deep class inheritance.

Defining and conforming to a protocol

Swift main.swift
protocol Describable {
    func describe() -> String
}

struct Product: Describable {
    let name: String
    let price: Double

    func describe() -> String {
        return "\(name): $\(price)"
    }
}

let item = Product(name: "Keyboard", price: 49.99)
print(item.describe())
Output
Keyboard: $49.99

Product: Describable is a promise: "this struct implements everything Describable requires." If Product were missing describe(), that would be a compile error, not something discovered later at runtime.

Protocols as types

Swift main.swift
struct Service: Describable {
    func describe() -> String { "A support service" }
}

let items: [Describable] = [
    Product(name: "Mouse", price: 19.99),
    Service()
]

for item in items {
    print(item.describe())
}
Output
Mouse: $19.99
A support service

An array typed as [Describable] can hold completely unrelated types — a Product struct and a Service struct share no inheritance relationship at all — as long as each one conforms to the protocol.

Extensions: adding behavior to an existing type

Swift main.swift
extension Int {
    var isEven: Bool {
        return self % 2 == 0
    }
}

print(4.isEven)
print(7.isEven)
Output
true
false

This adds a computed property, isEven, directly onto Int — a type built into Swift itself that you can't edit the source of. Extensions are how Swift's own standard library keeps growing without ever needing you to subclass anything.

Course complete: that covers the Swift course from top to bottom — variables and type inference, operators, conditionals including pattern-matching switch, loops, optionals and safe unwrapping, functions with argument labels, the struct-vs-class value/reference distinction, the three core collection types, and protocols with extensions. From here, the natural next step is Apple's own SwiftUI framework for building a real interface on top of what you've learned.