Structs, Classes, and Enums

Structs, Classes, and Enums in Swift: In a records office, most paperwork is handled as photocopies.

The Analogy: The Records Office

In a records office, most paperwork is handled as photocopies. When a clerk needs to give a colleague a customer's intake form, they run it through the copier and hand over the copy. The colleague can scribble corrections, cross out a field, or staple a note to their sheet, and none of it touches the clerk's original in the slightest. Two people now hold two independent pieces of paper that merely happened to start out identical. If a form is stamped "reference only", nobody may write on it at all; to make edits you must first be holding your own working copy and a pen.

A few records are too central to photocopy. The master account ledger is a single heavy book chained to the counter, and you never get the book itself; you get a numbered claim ticket that reads "counter ledger, page twelve". Every clerk holding a ticket for page twelve is looking at the exact same page, so when one of them writes "balance updated" there, everyone else who consults their ticket sees the new line immediately. Handing your ticket to a colleague does not copy the ledger, it simply gives them another pointer to the one book on the chain.

The office also keeps a category stamp with a fixed carousel of settings, and each setting has a small box to ink in a measurement: CIRCLE with a radius, RECTANGLE with a width and a height, TRIANGLE with a base and a height, and nothing else. A clerk reading a stamped ticket must have a rule for every setting on the carousel, because the stamp can only ever be one of those known positions. Two photocopies that read the same are counted as equal even though they are separate sheets, whereas two claim tickets are "the same" only when they name the very same chained book, not merely a book that happens to look alike.

The failure that catches everyone is forgetting which kind of thing they are holding. A clerk photocopies what they assume is an ordinary form, marks it up freely, and only later realises the "form" was actually a claim ticket to the chained ledger, so their casual edits quietly rewrote the master book that three other departments depend on. The reverse bites just as hard: someone hands out what they think are shared tickets, but they were photocopies, so the "shared" correction everyone was waiting for silently lived and died on one person's private sheet. Knowing whether a thing copies or shares is not a fussy detail; it decides who sees your changes.


Syntax or Core Structure

Swift gives you three named type-building keywords, and the one you pick decides how instances behave when they are assigned or passed around. A struct and an enum are value types: an assignment hands over an independent photocopy. A class is a reference type: an assignment hands over another claim ticket to one shared instance.

// A struct: a value type. Assigning it makes a copy.
struct Point {
    var x: Double
    var y: Double
    // Because a struct is a value type, a method that changes a
    // stored property must be marked mutating.
    mutating func moveRight(by dx: Double) {
        x += dx
    }
}

// A class: a reference type. Assigning it shares one instance.
class Counter {
    var count = 0
    func increment() { count += 1 }   // no mutating keyword needed
}

// An enum: a value type that models a closed set of cases,
// each of which may carry associated values.
enum Shape {
    case circle(radius: Double)
    case rectangle(width: Double, height: Double)
}

var a = Point(x: 0, y: 0)
var b = a          // b is a separate copy of a
b.moveRight(by: 5) // only b changes

let shared = Counter()
let alias = shared // alias points at the same Counter as shared
alias.increment()  // shared.count is now 1 too

The two facts to hold onto: a struct/enum value is copied on assignment so edits stay local, while a class instance is shared so edits are visible through every reference. Everything else in this lesson follows from that single distinction.


Technical Depth: Value Semantics, Identity, and Algebraic Enums

The choice between a struct, a class, and an enum is not stylistic. It changes what an assignment means, whether a let binding blocks mutation, and how you compare two things for sameness. This section works through each of those in turn.

Structs copy, classes share

When you assign a value type, Swift copies it; the copy and the original are from then on unrelated. When you assign a reference type, Swift copies only the pointer, so both names refer to one instance and a change through either is seen through both.

KindExamplesWhat assignment does
Value typestruct, enum, tuple, Int, String, Arraycopies the whole value
Reference typeclass, closureshares one instance
struct Tally { var n = 0 }
class Box { var n = 0 }

var a = Tally()
var b = a       // copy: b is independent of a
b.n = 5
print(a.n, b.n) // a is untouched

let x = Box()
let y = x       // share: y is the same object as x
y.n = 5
print(x.n, y.n) // x sees the change through y

Output:

0 5
5 5

The struct line prints 0 5 because b = a photocopied the tally, so writing b.n = 5 never reached a. The class line prints 5 5 because y = x handed out a second claim ticket to one Box, so y.n = 5 rewrote the very object x still names.

What a let really freezes

A let binding always forbids reassigning the name. What it does to the contents depends on the type. For a value type, the whole value is frozen, so you cannot even change a stored property or call a mutating method. For a reference type, only the pointer is frozen: you may not point it at a different instance, but you may freely mutate the instance it already points at.

DeclarationReassign the name?Mutate stored properties?
let s = SomeStruct()nono
var s = SomeStruct()yesyes (mutating method allowed)
let c = SomeClass()noyes, through the reference
var c = SomeClass()yesyes
struct Temperature {
    var celsius: Double
    mutating func warm(by delta: Double) {
        celsius += delta
    }
}

var t = Temperature(celsius: 20.0)
t.warm(by: 2.5)
print(t.celsius)

let frozen = Temperature(celsius: 0.0)
// frozen.warm(by: 1.0)  // compile error: frozen is a let value type
print(frozen.celsius)

Output:

22.5
0.0

t is a var, so warm(by:) is allowed and 20.0 + 2.5 prints 22.5. frozen is a let struct, so the commented call would not compile at all; the value stays exactly as constructed and prints 0.0. This is why Swift programmers reach for let and structs by default: the compiler turns "this should not change" into a rule it enforces, not a comment it ignores.

Enums with associated values are the workhorse

A Swift enum is not just a list of names. Each case can carry its own associated values, so an enum models a set of mutually exclusive alternatives that each hold different data. A switch over the enum binds those values and, because the case set is closed, the compiler forces you to handle every one.

enum Shape {
    case circle(radius: Double)
    case rectangle(width: Double, height: Double)

    var area: Double {
        switch self {
        case .circle(let r):
            return 3.14 * r * r
        case .rectangle(let w, let h):
            return w * h
        }
    }
}

let shapes: [Shape] = [
    .circle(radius: 2.0),
    .rectangle(width: 3.0, height: 4.0)
]
for shape in shapes {
    print(shape.area)
}

Output:

12.56
12.0

The circle carries a radius of 2.0, so its area is 3.14 * 2.0 * 2.0, which is 12.56. The rectangle carries a width and height, so its area is 3.0 * 4.0, which prints as 12.0 in Swift's shortest round-trippable form. If you later added a case triangle, the switch inside area would stop compiling until you handled it, which is exactly the exhaustiveness the coin-sorting catch-all bin gave you in an earlier lesson, now enforced at the type level.

Identity versus equality

Because a class instance is shared, Swift lets you ask two different questions about two references. The == operator asks whether the values are considered equal, which you define. The === operator asks whether the two references point at the very same instance. For value types === does not even apply, since there is no shared instance to identify.

class Widget: Equatable {
    let id: Int
    init(_ id: Int) { self.id = id }
    static func == (a: Widget, b: Widget) -> Bool {
        return a.id == b.id
    }
}

let w1 = Widget(1)
let w2 = Widget(1)
let w3 = w1

print(w1 == w2)   // equal by id
print(w1 === w2)  // but not the same object
print(w1 === w3)  // w3 is the same object as w1

Output:

true
false
true

w1 == w2 is true because both widgets carry id 1 and that is how we defined equality. w1 === w2 is false because they are two separate photocopies that merely read alike. w1 === w3 is true because w3 = w1 handed out another claim ticket to the one instance. Mixing these up is a classic bug: comparing with == when you meant identity lets two look-alike objects pass as one.


Real World Example: A Bank Account Ledger

A bank account is the textbook case for choosing types deliberately. Each money amount should be an immutable, self-contained value, so Money is a struct. The kinds of transaction form a fixed, closed set that each carry different data, so Transaction is an enum with associated values. But an account is a shared thing that many parts of a program hold and update together, so Account is a class, and every holder of it sees one balance.

struct Money {
    let cents: Int
    var text: String {
        let dollars = cents / 100
        let remainder = cents % 100
        let padded = remainder < 10 ? "0\(remainder)" : "\(remainder)"
        return "$\(dollars).\(padded)"
    }
}

enum Transaction {
    case deposit(Money)
    case withdraw(Money)
    case interest(rate: Double)
}

class Account {
    let owner: String
    private(set) var balanceCents: Int

    init(owner: String, opening: Money) {
        self.owner = owner
        self.balanceCents = opening.cents
    }

    func apply(_ tx: Transaction) {
        switch tx {
        case .deposit(let money):
            balanceCents += money.cents
        case .withdraw(let money):
            balanceCents -= money.cents
        case .interest(let rate):
            balanceCents += Int(Double(balanceCents) * rate)
        }
    }

    var balance: Money { Money(cents: balanceCents) }
}

let account = Account(owner: "Ada", opening: Money(cents: 10000))
let shared = account

let ledger: [Transaction] = [
    .deposit(Money(cents: 2500)),
    .withdraw(Money(cents: 4000)),
    .interest(rate: 0.10)
]

for tx in ledger {
    account.apply(tx)
}

print("account balance: \(account.balance.text)")
print("shared balance:  \(shared.balance.text)")

Output:

account balance: $93.50
shared balance:  $93.50

The three type choices each do a job here. Money is a struct, so every amount is an independent value that no other part of the program can reach in and change. Transaction is an enum, so a transaction is always exactly one of deposit, withdraw, or interest, and the switch inside apply must handle all three or fail to compile. Account is a class, so let shared = account does not make a second account; it makes a second name for the one account.

Following the numbers: the account opens at 10000 cents. The deposit of 2500 raises it to 12500. The withdrawal of 4000 lowers it to 8500. The interest case computes Int(Double(8500) * 0.10), which is Int(850.0), or 850, bringing the balance to 9350. The text property then splits 9350 into 93 dollars and 50 cents and prints $93.50.

The second print line is the whole point of reference semantics. We never applied a single transaction to shared; we only ever mutated account. Yet shared.balance.text also reports $93.50, because shared was a claim ticket to the same chained ledger all along. Had Account been a struct, shared would have been a photocopy taken at opening and would still read $100.00.

The genuine flaw in this code is that .withdraw subtracts with no overdraft guard. balanceCents -= money.cents will happily drive the balance negative, and Money.text was written assuming a non-negative amount: a balance of -50 cents would compute dollars = 0, remainder = -50, and print the nonsense $0.-50. The .interest case hides a second problem, since Int(...) truncates toward zero and quietly discards the fractional cent on every interest posting. Both bugs are invisible in this run because the sample ledger never overdraws and the one interest amount happens to be whole; a real ledger would need apply to return a success-or-failure result and a defined rounding rule for interest.


Common Mistakes

  1. Assuming a struct is shared. You pass a struct into a function, the function changes it, and you expect the caller's copy to change too. It will not: the function received a photocopy. If the caller needs to see the change, either return the modified value or pass it inout.
  1. Assuming a class is copied. The mirror image: you write let b = a on a class instance, edit b, and are surprised a changed as well. Both names are claim tickets to one object. When you truly need an independent instance, you must copy it yourself.
  1. Reaching for a class out of habit. Programmers coming from class-only languages make everything a class and then fight shared-mutation bugs for the rest of the project. In Swift the default should be a struct; promote to a class only when you genuinely need shared identity or inheritance.
  1. Forgetting the mutating keyword. A struct method that assigns to a stored property will not compile unless it is marked mutating. The error message is clear once you have seen it, but it puzzles people who expect methods to change their instance freely as they do in class-based languages.
  1. Mutating a stored property of a let struct. With a class, let only freezes the reference, so you can still call mutating-looking methods. With a struct, let freezes the whole value, so let p = Point(); p.x = 1 is a compile error. The same let behaves differently depending on the type.
  1. Confusing == with === on classes. == compares by whatever equality you defined; === asks whether two references are the same instance. Using == when you meant identity lets two look-alike objects pass as one, and using === when you meant equality reports two equal-but-separate objects as different.
  1. Defeating enum exhaustiveness with default. A switch over an enum without a default forces you to handle every case, so adding a new case makes the compiler point you at every switch that must be updated. Sprinkling default: everywhere throws that safety away: new cases silently fall into the default and go unhandled.
  1. Not binding an enum's associated values. Writing case .circle: when you actually needed the radius discards the data the case carries. You must bind it, as in case .circle(let radius):, to use the value inside the branch.
  1. Trying to subclass a struct or enum. Inheritance in Swift is a class-only feature. If you write struct Dog: Animal expecting Animal to be a base struct, it will not compile. Model shared behaviour for value types with protocols and extensions instead, which the next lesson covers.

Best Practices

  • Default to a struct. Reach for a struct first and promote to a class only when you actually need shared identity or inheritance. Value types make code easier to reason about because a value cannot be changed behind your back by code holding another reference.
  • Prefer let over var. Bind properties and locals with let unless they must change. On a struct this makes the whole value immutable; the compiler then guarantees nothing mutates it, which removes an entire class of bugs before it can start.
  • Model closed sets as enums with associated values. When a value is always exactly one of a fixed set of shapes, states, or results, an enum with associated values captures that precisely and lets the compiler enforce that every case is handled.
  • Keep enum switches exhaustive. For enums you own, avoid a default case. Handling every case explicitly means that when you add a new one, the compiler lists every switch that now needs attention instead of letting the new case slip silently into a default.
  • Restrict who can mutate a class. When only the type itself should change a stored property, declare it private(set), as Account does with balanceCents. Callers can read the balance but can only change it by going through apply, which keeps the invariants in one place.
  • Say identity or equality on purpose. Use === when you mean "the same instance" and == when you mean "equal by value". Define Equatable deliberately so == compares the fields that actually matter, and never let one stand in for the other by accident.
  • Keep structs small and composed. Because value types are copied, prefer several small, focused structs over one sprawling one, and build larger values by composing them. Small values are cheap to copy and easy to reason about in isolation.
  • Share behaviour with protocols, not forced class hierarchies. When several value types should share capabilities, define a protocol and provide default implementations in an extension rather than turning them into classes just to inherit. This keeps value semantics while still sharing code.

Practice Exercises

  1. Prove the copy/share split. Define a struct Ticket { var n = 0 } and a class Pass { var n = 0 }. Make a value of each, assign it to a second name, change the second name's n to 9, then print all four numbers. Confirm the struct pair prints 0 9 and the class pair prints 9 9, and write one sentence explaining why.
  1. Model media with an enum. Write enum Media with cases book(pages: Int) and movie(minutes: Int), and add a computed property estimatedMinutes that returns pages * 2 for a book and minutes for a movie. Build an array holding one of each, loop over it, and print the estimate for each. Predict the output before you would run it.
  1. Feel the difference let makes. Write a struct Odometer with a var miles: Double and a mutating func drive(_ d: Double). Create one with var and drive it, then create one with let and note (as a comment) which line fails to compile and why. Then show that a let instance of a class with the same method does compile.
  1. Repair the ledger flaw. Take the Account from the Real World Example and change apply so that .withdraw refuses a withdrawal larger than the balance and reports the failure to the caller instead of going negative, and so that .interest uses an explicit rounding rule rather than truncating. State in a comment what your rounding rule does with a half-cent.