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
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 storedlet, avaror a computed property all satisfy it.{ get set }would require a settable property.any Describableis an existential type: "some value whose concrete type adoptsDescribable". 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:
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.
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.
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:
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?
- A stored
varonly - A readable
nameproperty — stored or computed - A setter only
- A static property
What is a protocol extension commonly used for?
- Adding stored properties
- Providing default implementations of requirements
- Making a protocol a class
- Inheriting from another class
Which keyword in var body: some View means 'one specific concrete type that conforms to View'?
anysomeSelfwhere