Skip to the workspace
Pebellslearn by building
Core Programming Concepts  ›  Lesson

Classes, Structs and Protocols

OOP 12 minStructs are value types that are copied, classes are reference types that are shared and can inherit, and protocols are requirements any type can adopt.

ios / Classes, Structs and Protocols

Explore each scene at your own pace.

01 · The rule

The rule

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.5

A 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 object

A 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.