AnyCompiler

Protocols

A protocol defines a set of methods or properties a type must provide. Unlike class inheritance, which only classes can use, both structs and classes can conform to a protocol — this is central to what Swift calls protocol-oriented programming: favoring lightweight protocol conformance over deep class hierarchies wherever possible.

protocol Shape {
    func area() -> Double
}
struct Circle: Shape {
    var radius: Double
    func area() -> Double {
        return Double.pi * radius * radius
    }
}
struct Square: Shape {
    var side: Double
    func area() -> Double {
        return side * side
    }
}
let shapes: [Shape] = [Circle(radius: 2), Square(side: 3)]
for shape in shapes {
    print(shape.area())
}
Output
12.566370614359172
9.0

Circle and Square are both structs — value types, with no shared base class at all — but because they both conform to Shape, an array of Shape can hold either one, and the loop calls each one's own area() implementation.

Next: enums — enums with associated values, genuinely more powerful than a typical named-constant enum.

Practice exercise

Define a protocol Named with a method getName() -> String. Define a struct Dog: Named with var dogName: String conforming to it. Write a function greet(_ n: Named) that prints "Hello, \(n.getName())", and call greet(Dog(dogName: "Rex")).