You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Structs and classes are the main building blocks for modelling data in Swift. This lesson covers their similarities, key differences, when to use each, and related concepts like properties, methods, and initialisers.
struct Point {
var x: Double
var y: Double
}
class Vehicle {
var make: String
var model: String
var year: Int
init(make: String, model: String, year: Int) {
self.make = make
self.model = model
self.year = year
}
}
// Structs get a free memberwise initialiser
var origin = Point(x: 0, y: 0)
// Classes require an explicit init
let car = Vehicle(make: "Tesla", model: "Model 3", year: 2024)
This is the most important distinction between structs and classes:
| Aspect | Struct (Value Type) | Class (Reference Type) |
|---|---|---|
| Assignment | Creates a copy | Creates a shared reference |
| Mutability | Requires var to modify | Modifiable even through let |
| Inheritance | Not supported | Supported |
| Deinitialiser | Not available | Available (deinit) |
| Identity | Compared by value | Compared by reference (===) |
| Memory | Typically stack | Heap (ARC managed) |
var pointA = Point(x: 1, y: 2)
var pointB = pointA // copies the value
pointB.x = 10
print(pointA.x) // 1 — unchanged
print(pointB.x) // 10
let carA = Vehicle(make: "Toyota", model: "Camry", year: 2023)
let carB = carA // shares the same instance
carB.model = "Corolla"
print(carA.model) // "Corolla" — both point to the same object
print(carA === carB) // true — same reference
struct Rectangle {
var width: Double
var height: Double
}
struct Rectangle {
var width: Double
var height: Double
var area: Double {
width * height
}
var perimeter: Double {
get { 2 * (width + height) }
set { width = newValue / 4; height = newValue / 4 }
}
}
class StepCounter {
var totalSteps: Int = 0 {
willSet {
print("About to set totalSteps to \(newValue)")
}
didSet {
print("Changed from \(oldValue) to \(totalSteps)")
}
}
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.