The Programming Shortcut: Swift
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about protocols and generics: describing what a type can do.
The safe way is the short way
Swift is a language where the careful version of a program is usually the shortest one too.
Apple introduced it in 2014 for the people who write apps for iPhones and Macs. Before Swift, those people wrote Objective-C, a language from the early 1980s that let you do almost anything and caught very little of it. Swift was built to catch those mistakes while you’re still typing, without making you type more to get the help. It’s open source now and runs on Linux and Windows as well, but you can still feel who it was made for: app writers on deadlines, who would rather hear about a bug from the compiler than from a user.
Much of that safety comes from one habit. Most languages ask of a value, what is this? Swift keeps asking a second question: what can this do? Apple’s own team gave a conference talk in 2015 called “Protocol-Oriented Programming in Swift”, and the standard library is built that way from top to bottom.
A protocol is how Swift writes down an answer to “what can this do?” Generics are how a function asks for one. Together they’re the idea in this article, and they travel well. Java, Go, C# and TypeScript call protocols interfaces, and Rust calls them traits. Learn the idea once, here, and you’ll recognize it in every one of them.
In practice, you get to write one function where you would have written five.
What you already have
| What you know | lux | Swift |
|---|---|---|
| a record | struct | struct |
| a value that might be missing | Option<int> | Int? |
| an enum whose cases carry data | enum with payloads | enum with associated values |
| taking an enum apart | match | switch |
| errors you expect | Result | throws, or Result |
A few notes on those rows, and then we can leave them alone.
A Swift struct is a value type: assigning one to a new variable copies it, so
two variables never share the same struct. That idea has its own article,
C#. Int? is Swift’s optional, a value that is either there or
nil, and Swift makes you check which before you use it; the fullest short
explanation of that idea lives in Rust. A Swift switch over an enum
must cover every case or it won’t compile, which is called
exhaustive matching.
If you know lux, you have a shortcut nobody else has. Write a small struct that
compares two points, and save it as point.lux:
struct Point {
x: int
y: int
}
let here = Point(x: 3, y: 4)
print(here == Point(x: 3, y: 4))
Now run lux convert swift point.lux and read what comes back:
struct Point: Equatable {
var x: Int
var y: Int
}
let here = Point(x: 3, y: 4)
print(here == Point(x: 3, y: 4))
Look at the first line. That : Equatable is a protocol, and lux had to add it.
In lux, any two structs of the same type can be compared with ==. In Swift,
only a type that promises it can be compared gets ==, and Equatable is
that promise. You’ve been relying on a protocol all along without ever writing
one down. This article is about writing them down.
Edit, then swift run
If you have Xcode on a Mac, you already have Swift. Otherwise, swift.org/install has an installer for macOS, Linux and Windows. Check that it worked:
swift --version
Everything happens through that one swift command. Make a folder for a
package, a folder Swift knows how to build and run:
mkdir Shapes
cd Shapes
swift package init --type executable
mv Sources/Shapes/Shapes.swift Sources/Shapes/main.swift
The init line writes a starter program. The mv line renames it, because a
file called main.swift is special: it runs from top to bottom, like a lux file
or a script, with no main function needed. Open Sources/Shapes/main.swift,
replace everything in it with this one line, and save:
print("Hello, shapes")
Then, from the Shapes folder:
swift run
The first run takes a few seconds while Swift builds things; after that it’s
quick. You’ll see a few lines about building, then Hello, shapes.
Every example below works the same way: edit main.swift, run swift run,
read what comes back. When Swift refuses, the error message is usually the most
useful thing on the screen, so read it before you change anything.
What it is, and what it can do
Every typed function makes a promise about its parameters. Write
func area(of c: Circle) and you’ve said what you’ll accept: a circle,
and nothing else. That’s precise. It’s also narrow. The day you want the same
function for squares, you have two familiar choices: write it again with
Square in it, or make one big enum with a case for every shape.
There’s a third choice. Instead of saying what the value is, say what it must be able to do. “Give me anything that can tell me its area.” That sentence is a protocol.
A protocol is a promise
Here’s that sentence in Swift, and two types that keep it:
protocol Shape {
func area() -> Double
}
struct Circle: Shape {
var radius: Double
func area() -> Double {
return 3.14159 * radius * radius
}
}
struct Square: Shape {
var side: Double
func area() -> Double {
return side * side
}
}
print(Circle(radius: 2).area())
print(Square(side: 3).area())
Put it in main.swift and swift run it. You’ll get 12.56636 and 9.0.
(Double is Swift’s floating-point number.)
Three things are going on. The protocol block lists requirements: what a
type must provide, with no code for how. It’s a job description, not a worker.
Each struct then says : Shape, which means “I promise to keep the Shape
protocol.” Swift calls this conforming. And each one keeps the promise by
writing an area method, which is a function written inside a type, where it
can read that type’s fields directly. A circle knows its radius; a square knows
its side. Each computes its area its own way, and the protocol doesn’t care how.
The compiler holds you to it
A promise is only useful if somebody checks it. Make a promise you don’t keep:
protocol Shape {
func area() -> Double
}
struct Triangle: Shape {
var base: Double
var height: Double
}
Swift won’t build it:
error: type 'Triangle' does not conform to protocol 'Shape'
note: protocol requires function 'area()' with type '() -> Double'
Notice who caught it, and when. Not a test, not a user, but the compiler, before anything ran. The note even tells you which requirement is missing.
The check works the other way too. A type that happens to have an area()
method, but never says : Shape, doesn’t count as a Shape. Swift wants the
promise said out loud. That’s a real difference from duck typing, where a
language only asks “does this have an area method?” at the moment you call
it; Python is the home of that idea. Go sits in between: its
interfaces are checked by the compiler, but a type satisfies one without saying
so.
One function for a whole family
If you’ve written lux, you’ve met the problem this solves. A lux function that joins two arrays of strings can’t join two arrays of numbers. You write it twice, and the only difference is the type. lux let you make your own types; Swift lets you say what a whole family of types has in common, and write one function for all of them.
Here is that join, written once:
func joined<T>(_ first: [T], _ second: [T]) -> [T] {
var out: [T] = []
for item in first {
out.append(item)
}
for item in second {
out.append(item)
}
return out
}
print(joined([1, 2], [3]))
print(joined(["ace"], ["king", "queen"]))
The new part is <T>. It’s a type parameter: a placeholder that stands where
a type would go, filled in fresh at every call. In the first call T is Int.
In the second it’s String. You don’t say so; Swift works it out from the
arguments. A function written with a type parameter is called generic, because
it’s written once for any type. (The _ before each parameter just means
callers don’t have to write its name.)
That’s the easy half. What can joined actually do with a T? Store it,
copy it, hand it back. That’s all, because T could be anything,
and Swift only lets you do what’s true of everything. Try finding the biggest
item in an array:
func largest<T>(_ items: [T]) -> T? {
if items.isEmpty {
return nil
}
var best = items[0]
for item in items {
if item > best {
best = item
}
}
return best
}
print(largest([3, 9, 4]) as Any)
Swift refuses: binary operator '>' cannot be applied to two 'T' operands.
It’s right. Not every type can be compared with >, and a T might be a type
with no idea what “bigger” means.
So narrow it down. Ask for any type at all, as long as it keeps one particular promise:
func largest<T: Comparable>(_ items: [T]) -> T? {
if items.isEmpty {
return nil
}
var best = items[0]
for item in items {
if item > best {
best = item
}
}
return best
}
if let biggest = largest([3, 9, 4]) {
print(biggest)
}
if let last = largest(["pear", "apple", "zucchini"]) {
print(last)
}
T: Comparable is a constraint. It reads “T can be any type that conforms
to Comparable,” and Comparable is a protocol from Swift’s standard library.
Its only requirement you have to write is <; <=, > and >= come with
default versions. Inside the function you may use only what the
constraint promises, and outside, Swift will only let callers pass types that
keep it. (if let unwraps an optional: the block runs only if a value is there,
with the name bound to it.)
This is where the two halves meet. A protocol describes an ability. A constraint asks for one. Generic code is code that says “I don’t care what you are, only what you can do,” and the compiler checks both sides of that deal.
Generics keep the type; any makes a box
Your own protocols work as constraints the same way. Back to shapes:
func larger<S: Shape>(_ a: S, _ b: S) -> S {
if a.area() >= b.area() {
return a
}
return b
}
let big = larger(Circle(radius: 1), Circle(radius: 3))
print(big.radius)
That prints 3.0. Look at what came back: a Circle, not a vague “some shape,”
so big.radius works. A generic function remembers which type it was handed.
The flip side is that S is one type per call. Ask
larger(Circle(radius: 1), Square(side: 2)) and Swift says conflicting arguments to generic parameter 'S' ('Circle' vs. 'Square'). Both arguments
must be the same kind of shape.
Sometimes you want a mix, though. A drawing has circles and squares. For that,
Swift has any:
let shapes: [any Shape] = [Circle(radius: 1), Square(side: 2)]
var total = 0.0
for shape in shapes {
total += shape.area()
}
print(total)
Think of any Shape as a box. It can hold a value of any type that conforms,
it remembers what’s inside, and it passes calls through to it. The price is that
you can only use what the protocol promises: shapes[0].radius won’t compile,
because a box labeled “Shape” doesn’t know it’s holding a circle.
So there’s a choice to make each time. Use a generic when you work on one type at
a time and want it back intact. Use any when you truly need a mix. Most
languages with interfaces make the same split under different names; Rust, for
example, writes them impl Trait and dyn Trait.
Your type, the library’s code
Comparable isn’t magic reserved for numbers and strings. It’s
an ordinary protocol, and your types can keep it too:
struct Planet: Comparable {
var name: String
var moons: Int
static func < (a: Planet, b: Planet) -> Bool {
return a.moons < b.moons
}
}
let planets = [
Planet(name: "Earth", moons: 1),
Planet(name: "Mars", moons: 2),
Planet(name: "Venus", moons: 0),
]
for planet in planets.sorted() {
print(planet.name)
}
if let most = planets.max() {
print("Most moons:", most.name)
}
That prints Venus, Earth, Mars, and then Most moons: Mars. You wrote one
function: what < means for planets. (It’s static because it belongs to the
type rather than to any one planet, which is how Swift writes operators.) In
return, sorted() and max() started working on your type, and so would the
largest function from earlier. Somebody wrote those generic functions long ago
against the Comparable promise. They never heard of planets, and they didn’t
need to.
Comparable also needs ==, through Equatable, but Swift writes that one for
you when every field can already be compared. That’s what lux leaned on back in
the converted Point.
Protocols can hand out free behavior as well. An extension adds code to an existing type or protocol, and an extension on a protocol gives every conforming type the new method at once:
extension Shape {
func describe() -> String {
return "a shape with area \(area())"
}
}
print(Square(side: 3).describe())
Circle and Square never wrote describe, and both have it. (The \( )
inside a string drops a value into the text.) The standard library does this
constantly, as the hint at the end will show you.
A closed list or an open family
You may be thinking that an enum could do some of this. In lux you’d write
enum Shape with a circle case and a square case, and take it apart with
match. That’s a sum type, a value that is exactly one of a fixed list of
cases (Rust is its home), and it’s a fine design. It’s just a
different promise.
An enum is a closed list. Every case is known in one place, so the compiler can
check that each switch covers them all. Adding a new function over shapes is
easy. Adding a new shape means visiting every switch you’ve written.
A protocol is an open family. Anyone can add a new conforming type later, in another file, without touching a line of existing code. Adding a new shape is easy. Adding a new requirement means visiting every type.
Neither one wins. Ask which you expect to grow: the kinds of things, or the things you do with them.
Against the grain
Swift’s checks are strong, and nearly every one has a one-character exit. It’s
!.
You’ve seen that a box of any Shape hides what’s inside. You can ask to open
it. shape as? Circle is the careful way: it gives you an optional, a circle if
it was one and nil if not. shape as! Circle is the other way. It says “trust
me,” and if you’re wrong, the program stops:
protocol Shape {
func area() -> Double
}
struct Circle: Shape {
var radius: Double
func area() -> Double { return 3.14159 * radius * radius }
}
struct Square: Shape {
var side: Double
func area() -> Double { return side * side }
}
let shapes: [any Shape] = [Circle(radius: 1), Square(side: 2)]
let second = shapes[1] as! Circle
print(second.radius)
Could not cast value of type 'Shapes.Square' (0x…) to 'Shapes.Circle' (0x…).
The same ! on an optional, like largest([Int]())!, crashes on an empty array.
The compiler checked everything it could and then took your word for the rest.
Each ! is a spot where you’ve told Swift to stop checking. Reach for as? and
if let first.
Beware of SwiftUI before protocols make sense. SwiftUI is Apple’s way of building app screens, and it’s the first thing many people try. Its starter code looks like this:
struct ContentView: View {
var body: some View {
Text("Hello")
}
}
Every part of that is this article. View is a protocol. body is its
requirement. some View means “one particular type that conforms to View,
which I’m not going to name,” the mirror image of a generic parameter: there
the caller picks the type, here the function does. Start with SwiftUI and these
lines are an incantation you copy. Start with protocols, in a plain package like
the one you just made, and they read as ordinary code. Spend a week in plain
packages first. SwiftUI will still be there, and it will make sense.
A small project: packing a bag
The project is a bag you’re packing for a trip. Three very different types all keep one promise: each can tell you its name and its weight in grams. Then two generic functions work on any of them, and one function works on a mixed bag.
Make the package and rename its file, as before:
mkdir Pack
cd Pack
swift package init --type executable
mv Sources/Pack/Pack.swift Sources/Pack/main.swift
Replace everything in Sources/Pack/main.swift with this:
protocol Packable {
var name: String { get }
var grams: Int { get }
}
extension Packable {
func label() -> String {
return "\(name), \(grams) g"
}
}
struct Book: Packable {
var title: String
var pages: Int
var name: String { title }
var grams: Int { pages * 2 }
}
struct Bottle: Packable {
var milliliters: Int
var name: String { "water bottle" }
var grams: Int { 150 + milliliters }
}
enum Snack: Packable {
case apple
case trailMix(bags: Int)
case sandwich
var name: String {
switch self {
case .apple: return "apple"
case .trailMix(let bags): return "trail mix x\(bags)"
case .sandwich: return "sandwich"
}
}
var grams: Int {
switch self {
case .apple: return 180
case .trailMix(let bags): return 120 * bags
case .sandwich: return 250
}
}
}
func heaviest<Item: Packable>(_ items: [Item]) -> Item? {
if items.isEmpty {
return nil
}
var best = items[0]
for item in items {
if item.grams > best.grams {
best = item
}
}
return best
}
func fitting<Item: Packable>(_ items: [Item], under limit: Int) -> [Item] {
var packed: [Item] = []
var total = 0
for item in items {
if total + item.grams <= limit {
packed.append(item)
total += item.grams
}
}
return packed
}
func totalGrams(_ items: [any Packable]) -> Int {
var total = 0
for item in items {
total += item.grams
}
return total
}
let books = [
Book(title: "The Hobbit", pages: 310),
Book(title: "Dune", pages: 688),
Book(title: "A Wizard of Earthsea", pages: 183),
]
let snacks: [Snack] = [.apple, .trailMix(bags: 3), .sandwich]
if let book = heaviest(books) {
print("Heaviest book: \(book.label()), \(book.pages) pages")
}
if let snack = heaviest(snacks) {
print("Heaviest snack: \(snack.label())")
}
print("Books that fit in 1000 g:")
for book in fitting(books, under: 1000) {
print(" \(book.label())")
}
let bag: [any Packable] = [books[0], Bottle(milliliters: 750), Snack.apple, Snack.sandwich]
print("In the bag:")
for item in bag {
print(" \(item.label())")
}
print("Total: \(totalGrams(bag)) g")
Run swift run, and after the build lines you’ll see:
Heaviest book: Dune, 1376 g, 688 pages
Heaviest snack: trail mix x3, 360 g
Books that fit in 1000 g:
The Hobbit, 620 g
A Wizard of Earthsea, 366 g
In the bag:
The Hobbit, 620 g
water bottle, 900 g
apple, 180 g
sandwich, 250 g
Total: 1950 g
A few things to look for as you read it.
The protocol asks for properties this time, not methods. var grams: Int { get }
means “you must have a grams I can read,” and it doesn’t say how. Book
answers with a computed property, var grams: Int { pages * 2 }, which is a
field whose value is worked out each time it’s read. Bottle computes its own
way. Snack isn’t even a struct: it’s an enum, and it keeps the promise with a
switch. The protocol asked what, and each type chose how.
heaviest is one function, and it worked on books and on snacks. When you
handed it books, it handed back a Book, so book.pages compiles on the next
line. label() came free from the extension; none of the three types
wrote it.
The bag is a mix, so it’s [any Packable], and totalGrams takes the boxed
kind. Try heaviest(bag) and Swift says type 'any Packable' cannot conform to 'Packable'. That sounds strange until you remember the box: a generic function
needs one real type to fill in for Item, and a box of mixed things isn’t one.
The file in the series repository ends with more things to try.
What’s left out, and where to go next
This article left a lot of Swift out. Protocols can have their own
type placeholders, called associated types; that’s how a collection says what
kind of element it holds. Generic code can ask for several promises at once, or
add conditions with where. A type can be made to conform to a protocol after
the fact, in an extension. And Swift has classes, inheritance, its own approach
to concurrency, and a great deal more that isn’t about protocols at all.
When you want more, go to the people who make the language. The Swift Programming Language is the official book, free online, and its chapters on Protocols and Generics pick up where this article stops. swift.org/documentation has the rest.
Ask Swift what it promised
You made Planet comparable by writing one function, <. So where did >
come from? Ask Swift. In a terminal, start its interactive shell:
swift repl
Then type this, and press Return:
:type lookup Comparable
You’ll see the protocol itself: its requirements, the protocol it builds on, and
the extensions that hand out free behavior. Find < in the list, then find the
operators you never wrote. Then try :type lookup on Equatable, or on a type
you use every day, and ask of each one: what can this do, and who promised it?
Type :quit when you’re done.
Related
- C#: value and reference semantics, the reason a Swift struct is copied when you assign it.
- Rust: optionals, enums that carry data, and exhaustive matching, the closed-list side of the choice in this article.
- Python: duck typing, the opposite answer to “does this value keep the promise?”
Tested with Swift 6.2.4 and lux 0.21.2, November 2026.