Swift gives you three ways to define a type and the difference that matters most is not inheritance, it is copying. A struct is a value type: assigning it makes a copy, and the two copies have nothing to do with each other. A class is a reference type: assigning it copies the reference, so both names point at one object and a change through either is seen through both. An enum is a value type too, and in Swift it can carry associated values, which makes it the right tool for modelling a thing that is exactly one of several cases.
The guidance Apple gives, and the one this course follows, is to start with a struct. Use a class when you need identity (this is the same object, not an equal one), when you need inheritance, or when something must be shared deliberately. SwiftUI is built on value types from top to bottom: every view you write is a struct, and that is what makes the framework able to throw your view away and rebuild it sixty times a second without consequence.
A protocol is a list of requirements a type can promise to meet. Protocols are how Swift does polymorphism without inheritance: a struct cannot inherit, but it can conform. And because you can extend a protocol with default implementations, you can share behaviour across types that have no common ancestor - which is what "protocol-oriented programming" means in practice.
// A struct is copied. Change the copy and the original is untouched.
struct Point {
var x: Int
var y: Int
// Mutating, because a method that changes a value type must say so.
mutating func shiftRight(by amount: Int) { x += amount }
}
var p1 = Point(x: 1, y: 2)
var p2 = p1
p2.shiftRight(by: 8)
// p1.x is 1, p2.x is 9 - two separate boxes.
// A class is shared. Both names hold the same object.
class Counter {
var value = 0
func increment() { value += 1 }
}
let c1 = Counter()
let c2 = c1
c2.increment()
// c1.value is 1 as well - one object, two names.
// An enum with associated values models "exactly one of these".
enum LoadState {
case idle
case loading
case loaded(items: [String])
case failed(Error)
}
// A protocol is a promise, and an extension gives it a default.
protocol Describable {
var title: String { get }
}
extension Describable {
var shortLabel: String { String(title.prefix(8)) }
}
struct Task: Describable {
let title: String
}
print(p1.x, p2.x, c1.value, Task(title: "Write the tests").shortLabel)