TExcelTAD
Home › Swift › Swift Protocols

Swift Protocols

A protocol describes a set of requirements — properties and methods — without implementing them. Any struct, class or enum can adopt a protocol and promise to fulfil those requirements. Protocols are how Swift shares behaviour between unrelated types, which is why Swift is often called a protocol-oriented language.

Declaring and adopting a protocol

swift · try it yourself
protocol Describable {
    var name: String { get }          // a read-only property requirement
    func describe() -> String         // a method requirement
}

struct City: Describable {
    let name: String
    let population: Int

    func describe() -> String {
        "\(name) has \(population) people"
    }
}

enum Fruit: String, Describable {
    case mango, durian

    var name: String { rawValue.prefix(1).uppercased() + rawValue.dropFirst() }
    func describe() -> String { "\(name) is a fruit" }
}

let things: [any Describable] = [City(name: "Hue", population: 650_000), Fruit.durian]
for thing in things {
    print(thing.describe())
}
Hue has 650000 people
Durian is a fruit
  • { get } means the property must be readable; a stored let, a var or a computed property all satisfy it. { get set } would require a settable property.
  • any Describable is an existential type: "some value whose concrete type adopts Describable". It lets one array hold different types.

Protocols as function parameters

A function that accepts a protocol works with every adopting type — present and future:

swift · try it yourself
protocol Shape {
    func area() -> Double
}

struct Square: Shape {
    let side: Double
    func area() -> Double { side * side }
}

struct Rectangle: Shape {
    let width: Double
    let height: Double
    func area() -> Double { width * height }
}

func totalArea(_ shapes: [any Shape]) -> Double {
    shapes.reduce(0) { $0 + $1.area() }
}

func printArea(of shape: some Shape) {
    print("Area:", shape.area())
}

printArea(of: Square(side: 3))
printArea(of: Rectangle(width: 2, height: 1.5))
print("Total:", totalArea([Square(side: 2), Rectangle(width: 2, height: 3)]))
Area: 9.0
Area: 3.0
Total: 10.0

some Shape means "one specific type that conforms to Shape", decided by the caller. It is faster than any Shape and is the same keyword SwiftUI uses in var body: some View.

Mutating requirements

If a protocol method should be able to change a struct or enum, declare it mutating in the protocol. Classes implementing it simply omit the keyword.

swift · try it yourself
protocol Toggleable {
    mutating func toggle()
}

enum Switch: Toggleable {
    case on, off
    mutating func toggle() {
        self = (self == .on) ? .off : .on
    }
}

var lightSwitch = Switch.off
lightSwitch.toggle()
print(lightSwitch)
lightSwitch.toggle()
print(lightSwitch)
on
off

Protocol extensions: default implementations

A protocol extension can provide a default implementation. Adopting types get it for free, but may still provide their own version.

swift · try it yourself
protocol Greeter {
    var name: String { get }
    func greet() -> String
}

extension Greeter {
    func greet() -> String { "Hi, I'm \(name)." }
}

struct Student: Greeter {
    let name: String              // uses the default greet()
}

struct Robot: Greeter {
    let name: String
    func greet() -> String { "BEEP. UNIT \(name.uppercased()) ONLINE." }
}

print(Student(name: "Thu").greet())
print(Robot(name: "r2").greet())
Hi, I'm Thu.
BEEP. UNIT R2 ONLINE.

Standard library protocols

Many everyday features come from protocols you adopt. Often Swift can synthesize the implementation for you:

swift · try it yourself
struct Version: Comparable, CustomStringConvertible, Hashable {
    let major: Int
    let minor: Int

    static func < (a: Version, b: Version) -> Bool {
        (a.major, a.minor) < (b.major, b.minor)
    }

    var description: String { "v\(major).\(minor)" }
}

let versions = [Version(major: 2, minor: 1), Version(major: 1, minor: 9), Version(major: 2, minor: 0)]
print(versions.sorted())
print(versions.max()!)
print(Version(major: 1, minor: 9) == Version(major: 1, minor: 9))   // == synthesized
[v1.9, v2.0, v2.1]
v2.1
true
Protocol Gives you Synthesized?
Equatable == and != Yes, for structs/enums whose members are Equatable
Hashable Use in Set and as Dictionary key Yes, same condition
Comparable <, sorted(), max() Only for enums without associated values; otherwise write <
CustomStringConvertible Custom text for print No — write description
CaseIterable allCases Yes, for simple enums
Codable JSON encoding/decoding Yes

Tip: Name protocols for what a type is (Collection, Shape) or what it can do (Equatable, Codable, Toggleable).

Test yourself

What does var name: String { get } in a protocol require?

  1. A stored var only
  2. A readable name property — stored or computed
  3. A setter only
  4. A static property

What is a protocol extension commonly used for?

  1. Adding stored properties
  2. Providing default implementations of requirements
  3. Making a protocol a class
  4. Inheriting from another class

Which keyword in var body: some View means 'one specific concrete type that conforms to View'?

  1. any
  2. some
  3. Self
  4. where