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.