Classes, Structs and Protocols
TrailLog has a Hike (a record of one walk), a JournalStore (the one object that loads and saves all hikes), and several things that can be "shared" — hikes, photos, routes. Swift gives you three tools for modelling them, and choosing well is the heart of object-oriented design in iOS.
The rule
Structs are copied, classes are shared, protocols are promises.
A struct is a value type. Assigning or passing it makes an independent copy:
struct Hike {
var name: String
var distanceKm: Double
}
var a = Hike(name: "Ridge Loop", distanceKm: 8.5)
var b = a
b.distanceKm = 9.0
// a.distanceKm is still 8.5A class is a reference type. Assigning it copies a reference, so both names point at the same object. Classes also support inheritance — class ViewController: UIViewController inherits everything a view controller can do — and have identity (=== checks "same object").
final class JournalStore {
var hikes: [Hike] = []
}
let store = JournalStore()
let sameStore = store
sameStore.hikes.append(a)
// store.hikes.count is now 1 — it is one objectA protocol is a list of requirements that any type can promise to meet. Structs, classes and enums can all adopt protocols, which is how Swift shares behaviour without inheritance:
protocol Shareable {
var shareText: String { get }
}
extension Hike: Shareable {
var shareText: String { "I hiked \(name): \(distanceKm) km" }
}Now any function that accepts Shareable works with hikes, photos or routes alike. Swift's standard library leans on this style — Equatable, Codable, Hashable are all protocols.
The shortcut
Default to a struct. Choose a class only when you answer yes to: "Must many parts of the app see the same, changing instance?" or "Must I subclass an Apple class?" Use a protocol when unrelated types need the same ability.
Hike
A record of data; two screens editing their own copies is fine. No shared identity → struct.
The trap: making Hike a class "because it is an object". Then editing a hike in one screen silently edits it in every other screen holding it.
Drills
Answer fast — trust the rule.
Hike is a struct. After var b = a; b.name = "Lake Path", what is a.name?
Which type in a UIKit app must be a class?
Hikes, photos and routes all need a shareText property, but share nothing else. What fits best?
Two constants refer to the same JournalStore instance. One appends a hike. What does the other see?
Remember
- Structs are copied, classes are shared, protocols are promises any type can keep.
- Default to struct; use a class for shared identity or subclassing; a protocol for common abilities.
- Trap: a data model as a class leaks edits between screens.
