Code that works for many types
In the last lesson, Vehicle and Bicycle shared behaviour through inheritance. That only works for classes, only from one superclass, and it couples the subclass to every detail of its parent. Swift's main tool for sharing behaviour is different: a protocol describes what a type can do (its required properties and methods) without saying anything about how it stores its data. Any struct, enum or class can promise to fulfil a protocol, and a single type can fulfil as many protocols as it likes.
Protocols are everywhere in Swift. for x in something works because something conforms to Sequence. == works on your type if it conforms to Equatable; sorted() needs Comparable; putting a value in a Set needs Hashable; turning it into JSON needs Codable. Learning Swift's protocols is learning how the standard library is put together.
Two companions make protocols powerful. Extensions add methods and conformances to any type, including ones you did not write, like Int. Generics let you write a function or type once, with placeholders for types, constrained by protocols, so that the compiler can check and optimize each use. Together they are often called protocol-oriented programming, a phrase Apple introduced in a 2015 conference talk.
Protocols and protocol extensions
Definition— protocol
A protocol is a named list of requirements: properties (with { get } or { get set }), methods, initializers and associated types. A type conforms to a protocol by declaring it after a colon and meeting every requirement. A protocol extension can add methods to every conforming type at once, including default implementations of requirements.
protocol Shape {
var name: String { get }
func area() -> Double
}
// A protocol extension: every Shape gets these for free.
extension Shape {
func summary() -> String {
"\(name) with area \(area())"
}
func isLarger(than other: some Shape) -> Bool {
area() > other.area()
}
}
struct Square: Shape {
let side: Double
var name: String { "square" }
func area() -> Double { side * side }
}
struct Rectangle: Shape {
let width: Double
let height: Double
var name: String { "rectangle" }
func area() -> Double { width * height }
}
struct Triangle: Shape {
let base: Double
let height: Double
var name: String { "triangle" }
func area() -> Double { base * height / 2 }
// A type can replace a default implementation with its own.
func summary() -> String { "a triangle of base \(base)" }
}
let shapes: [any Shape] = [Square(side: 3), Rectangle(width: 2, height: 5), Triangle(base: 4, height: 3)]
for shape in shapes {
print(shape.summary())
}
let total = shapes.reduce(0) { $0 + $1.area() }
print("Total area:", total)
print(Triangle(base: 4, height: 3).summary())
print(Square(side: 3).isLarger(than: Triangle(base: 4, height: 3)))square with area 9.0
rectangle with area 10.0
triangle with area 6.0
Total area: 25.0
a triangle of base 4.0
trueThe three shape types share no superclass and no stored properties; each just promises name and area(). The protocol extension writes summary() and isLarger(than:) once, in terms of the requirements, and every shape has them. Add a fourth shape tomorrow and it gets them too.
[any Shape] is an array whose elements can be any type that conforms to Shape; the keyword any marks a protocol used as a type (an existential, explained below).
A trap worth knowing: requirements versus extension methods
Look at the third line of output. Triangle wrote its own summary(), yet in the loop the triangle printed the default text. Called directly on a Triangle, its own version runs (the fifth line). Why the difference?
summary() is not a requirement of Shape; it exists only in the extension. When the compiler sees shape.summary() on an any Shape, it knows only that the value is some shape, so it calls the one summary() it can see: the extension's. Methods that are requirements, like area(), are looked up at run time in the actual type's table of conformance methods, which is why each shape's own area() was used. The fix is to list func summary() -> String inside the protocol itself. Then the extension's version becomes a default, used only by types that do not write their own, and the triangle's override is found even through any Shape. Rule of thumb: if a conforming type might want to customize a method, make it a requirement.
A few more protocol tools
A requirement that changes a value type must be marked mutating in the protocol (mutating func reset()), so structs and enums can fulfil it; classes simply implement it without the keyword. A protocol can inherit from others (protocol Polygon: Shape { var sides: Int { get } }), and a type can be required to conform to several at once with composition, written with &: a parameter of type some Shape & CustomStringConvertible accepts only shapes that can also describe themselves. Finally, a protocol declared as protocol Delegate: AnyObject can only be adopted by classes, which you need when you want to hold a conforming value through a weak reference, a pattern you will meet in the memory lesson.
The standard protocols, mostly for free
For many standard protocols, Swift synthesizes the conformance: declare it and the compiler writes the code, as long as every stored property already conforms. Equatable compares each property, Hashable combines their hashes, and Codable (from Foundation) encodes each one by name. Comparable needs one function from you, <, because only you know what "smaller" means.
import Foundation
struct Version: Comparable, Hashable, Codable, CustomStringConvertible {
let major: Int
let minor: Int
let patch: Int
static func < (a: Version, b: Version) -> Bool {
(a.major, a.minor, a.patch) < (b.major, b.minor, b.patch)
}
var description: String { "\(major).\(minor).\(patch)" }
}
let releases = [
Version(major: 6, minor: 1, patch: 0),
Version(major: 5, minor: 10, patch: 1),
Version(major: 6, minor: 0, patch: 3),
Version(major: 6, minor: 1, patch: 0),
]
print(releases.sorted())
print(releases.max() ?? Version(major: 0, minor: 0, patch: 0), Set(releases).count)
print(releases[0] == releases[3], releases[1] < releases[2])
// Extensions add behaviour to types you did not write.
extension Int {
var isEven: Bool { self % 2 == 0 }
}
extension Array where Element: Numeric {
func total() -> Element { reduce(0, +) }
}
print(7.isEven, [1.5, 2.5, 3.0].total(), [4, 5, 6].total())
// Codable conformance is synthesized too.
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let json = try encoder.encode(releases[0])
print(String(decoding: json, as: UTF8.self))
let back = try JSONDecoder().decode(Version.self, from: json)
print(back == releases[0])[5.10.1, 6.0.3, 6.1.0, 6.1.0]
6.1.0 3
true true
false 7.0 15
{"major":6,"minor":1,"patch":0}
truesorted(),max()and<work because ofComparable; the comparison uses tuple ordering to compare major, then minor, then patch numbers. Version 5.10.1 sorts before 6.0.3, which string comparison would get wrong.Set(releases).countis 3 because the two 6.1.0 values are equal and hash alike: synthesizedHashableat work.printusesdescriptionfromCustomStringConvertible.extension Intadds a computed property to a standard type.extension Array where Element: Numericaddstotal()only to arrays of numbers: an array of strings simply has nototal()method. This is a constrained extension.JSONEncoderandJSONDecodercome from Foundation, hence theimport. Thetrykeyword marks calls that can fail; the errors lesson explains it. Codable is how most Swift apps talk to web services.
Identifiable (a type with a stable id) and Sendable (safe to share across concurrent code) are two more protocols you will meet constantly, the second in the concurrency lesson.
Generics
A generic function or type has type parameters: placeholders, written in angle brackets after the name, that the caller fills in. A constraint such as T: Comparable says which protocols the placeholder must conform to, and therefore what the code may do with it.
// A generic type: a stack of any kind of element.
struct Stack<Element> {
private var items: [Element] = []
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element? {
items.popLast()
}
var top: Element? { items.last }
var isEmpty: Bool { items.isEmpty }
}
// Conditional conformance: a Stack is printable when its elements are.
extension Stack: CustomStringConvertible where Element: CustomStringConvertible {
var description: String {
"[" + items.map(\.description).joined(separator: ", ") + "] (top is last)"
}
}
// A generic function with a constraint.
func largest<T: Comparable>(_ items: [T]) -> T? {
guard var best = items.first else { return nil }
for item in items.dropFirst() where item > best {
best = item
}
return best
}
var plates = Stack<String>()
plates.push("blue")
plates.push("green")
plates.push("red")
print(plates)
print(plates.pop() ?? "none", plates.top ?? "none")
var numbers = Stack<Int>()
numbers.push(42)
print(numbers, numbers.isEmpty)
print(largest([3, 9, 2]) ?? 0, largest(["fig", "apple", "kiwi"]) ?? "", largest([Double]()) == nil)
// Checking balanced brackets with a Stack of Characters.
func isBalanced(_ text: String) -> Bool {
let pairs: [Character: Character] = [")": "(", "]": "[", "}": "{"]
var open = Stack<Character>()
for ch in text {
if "([{".contains(ch) {
open.push(ch)
} else if let expected = pairs[ch] {
guard open.pop() == expected else { return false }
}
}
return open.isEmpty
}
print(isBalanced("f(a[1], {b: 2})"), isBalanced("(]"), isBalanced("(("))[blue, green, red] (top is last)
red green
[42] (top is last) false
9 kiwi true
true false falseStack is written once, for an element type called Element, and used as a stack of strings, of integers and of characters. Inside, it can only store and return elements, because Element has no constraints. The extension below it is a conditional conformance: a stack is CustomStringConvertible when its elements are. The standard library uses the same technique for Array: an array is Equatable when its elements are, which is why [1, 2] == [1, 2] compiles while two arrays of shapes cannot be compared with ==. The standard library's Array, Dictionary, Optional and Result are all generic types built this way.
largest is a generic function whose constraint, Comparable, is exactly what it needs to use >. It works for integers and strings, and for the empty array of Double it returns nil. The compiler checks each call: largest([Shape]) would be rejected, since shapes are not comparable.
Generics are not slower than hand-written code. In an optimized build, when the compiler can see the concrete type at a call site, it specializes the generic code for that type, producing the same machine code as if you had written a version for Int by hand.
Associated types and Sequence
A protocol can have an associated type, a placeholder that each conforming type fills in. Sequence has one called Element. Conform to it, and the standard library's protocol extensions give your type dozens of methods:
// Conforming to Sequence and IteratorProtocol unlocks for-in, map, filter, reduce...
struct Countdown: Sequence, IteratorProtocol {
var current: Int
mutating func next() -> Int? {
guard current > 0 else { return nil }
defer { current -= 1 }
return current
}
}
for n in Countdown(current: 3) {
print(n, terminator: " ")
}
print("liftoff!")
let evens = Countdown(current: 10).filter { $0 % 2 == 0 }
print(evens, Countdown(current: 4).reduce(0, +), Countdown(current: 5).contains(6))
// A generic function over any Sequence, using its associated type Element.
func countMatches<S: Sequence>(in items: S, where test: (S.Element) -> Bool) -> Int {
var count = 0
for item in items where test(item) {
count += 1
}
return count
}
print(countMatches(in: Countdown(current: 9)) { $0 > 6 })
print(countMatches(in: "Mississippi") { $0 == "s" })3 2 1 liftoff!
[10, 8, 6, 4, 2] 10 false
3
4Countdown writes one method, next(), returning nil when it is finished; defer runs its block just before the function returns, so current is decremented after the value has been returned. Everything else (for-in, filter, reduce, contains) comes from extensions on Sequence. countMatches is generic over any sequence and refers to its element type as S.Element; it works on a countdown and on a string alike, since a String is a sequence of Character.
some and any
Swift has two ways to use a protocol where a type is expected, and the difference matters for both design and speed.
Definition— opaque type (some)
some Shape means "one specific type that conforms to Shape, which the compiler knows but the code does not name". In a parameter, some Shape is shorthand for a generic parameter. As a return type, it hides the concrete type from callers while keeping it fixed.
Definition— existential type (any)
any Shape means "a box that can hold a value of any conforming type, possibly a different one each time". The concrete type is known only at run time.
func describe(_ s: some Shape) -> String // generic: one concrete type per call, specialized
func describe(_ s: any Shape) -> String // existential: a box, with dynamic dispatch
func makeShape() -> some Shape { Square(side: 2) } // callers know only "some Shape"
let mixed: [any Shape] = [Square(side: 1), Triangle(base: 2, height: 2)]Use some (or an explicit generic parameter) by default: it is checked and optimized at compile time. Use any when you genuinely need different types together, as in the heterogeneous array mixed. An existential stores small values inline and larger ones on the heap, and calls go through a table, so it costs a little more, and it loses some type information: you cannot, for example, compare two any Equatable values with ==, because they might be different types. SwiftUI's var body: some View is the most famous use of some: the real type of a screen's view tree is enormous and nobody wants to write it.
Since Swift 5.6 you write any explicitly; older code wrote just Shape for the existential, and the compiler still accepts that in the Swift 5 and 6 language modes. The toolchain already lists requiring any as an upcoming feature for a future language mode, so new code should always write it.
Common misconceptions
Misconception
"A method in a protocol extension can be overridden like a class method." Only requirements are dynamically dispatched. A method that exists only in an extension is chosen by the static type, as the triangle showed. Declare it in the protocol if conforming types should be able to replace it.
Misconception
"Protocols are just Java interfaces." They overlap, but Swift protocols can be adopted by value types, can be added to existing types retroactively with an extension, can have associated types and Self requirements, can provide implementations through extensions, and can be used as constraints on generics with no runtime cost.
Misconception
"any and some are interchangeable." some fixes one concrete type (chosen by the caller for a parameter, by the function for a return value) and is fully optimized. any is a runtime box that can hold different types. A function returning some Shape must always return the same concrete type; one returning any Shape may return a square on Monday and a triangle on Tuesday.
How professionals use them
In a large Swift codebase, protocols mark the seams. A service that talks to a server is described by a protocol (protocol WeatherService { func forecast(for city: String) async throws -> Forecast }), the real implementation conforms to it, and tests substitute a fake that returns canned data. Extensions organize code: many teams put each protocol conformance in its own extension Type: Protocol { ... } block, so a type's file reads as a list of capabilities. And generic code is kept for real reuse: the standard library and widely used packages are heavily generic, while application code is mostly concrete, with generics used where they remove real duplication. Overly abstract protocol hierarchies, with protocols that have one conforming type, are a recognized smell; start concrete, and extract a protocol when a second implementation (often a test double) appears.
Exercises
1. Protocols, extensions and generics
StretchComputationalWhat does this program print?
protocol Greeter { func hello() -> String }
extension Greeter {
func hello() -> String { "hello" }
func wave() -> String { "wave" }
}
struct Polite: Greeter {
func hello() -> String { "good day" }
func wave() -> String { "bow" }
}
let g: any Greeter = Polite()
print(g.hello(), g.wave(), Polite().wave())
2. Protocols, extensions and generics
Warm-upComputationalWhat does this print?
struct Point: Hashable { let x: Int; let y: Int }
let pts: Set = [Point(x: 1, y: 2), Point(x: 2, y: 1), Point(x: 1, y: 2)]
print(pts.count)
3. Protocols, extensions and generics
CoreComputationalWhat does this program print?
func pairUp<T>(_ a: [T], _ b: [T]) -> [[T]] {
zip(a, b).map { [$0, $1] }
}
print(pairUp([1, 2, 3], [4, 5]))
4. Protocols, extensions and generics
CoreComputationalThis function does not compile: binary operator '<' cannot be applied to two 'T' operands.
func smallest<T>(_ xs: [T]) -> T? {
guard var best = xs.first else { return nil }
for x in xs where x < best { best = x }
return best
}
What is the smallest change that fixes it?
5. Protocols, extensions and generics
CoreHumanmakeShape(round:) should return a Circle when round is true and a Square otherwise. Which return type works?
6. Protocols, extensions and generics
CoreComputationalWhat does this program print?
struct Evens: Sequence, IteratorProtocol {
var n = 0
let limit: Int
mutating func next() -> Int? {
n += 2
return n <= limit ? n : nil
}
}
print(Evens(limit: 7).map { $0 * 10 })
7. Protocols, extensions and generics
CoreHumanYou have just written protocol Describable { var summary: String { get } }. Which of these can you make conform to it in your own code? List the letters.
- A. A struct you wrote
- B. An enum you wrote
- C. A class from a library you depend on
- D. The standard library's
Int - E. The tuple type
(Int, Int)
Further reading and resources
- The Swift Programming Language: Protocols, Extensions, Generics, Opaque and Boxed Types
- WWDC 2015: Protocol-Oriented Programming in SwiftThe talk that introduced the phrase "protocol-oriented programming".
- SE-0335: Introduce existential anyWhy Swift asks you to write any in front of a protocol used as a type.
- Encoding and Decoding Custom TypesHow Codable works, including custom keys and nested data.