Three ways to make a type
Most of a real program is made of types its authors defined: a Temperature, an Account, a Payment, an Order. Swift gives you three main ways to define one, and choosing between them is a design decision you make every day.
- A struct bundles values together. It is a value type: assigning it or passing it to a function copies it.
- A class also bundles values, and adds inheritance. It is a reference type: assigning it shares one object between several names.
- An enum says that a value is exactly one of a fixed list of alternatives, each of which may carry its own data.
In most object-oriented languages, everything you define is a class. Swift turns that upside down. Int, Double, String, Array, Dictionary, Set and Optional are all structs or enums, and Apple's guidance is to use a struct by default and a class only when you need what only a class can do. This lesson explains why, by showing what value semantics buys you and what it costs.
Structs
A struct declares stored properties (the data it holds), and can add computed properties (worked out on demand), methods, and initializers. If you write no initializer, Swift generates a memberwise initializer that takes every stored property by name.
struct Temperature {
var celsius: Double
// A computed property: no storage, worked out on demand.
var fahrenheit: Double {
get { celsius * 9 / 5 + 32 }
set { celsius = (newValue - 32) * 5 / 9 }
}
// A method that changes the struct must be marked mutating.
mutating func warm(by degrees: Double) {
celsius += degrees
}
}
var today = Temperature(celsius: 21) // the memberwise initializer, for free
var tomorrow = today // a copy
tomorrow.warm(by: 4)
print(today.celsius, tomorrow.celsius, tomorrow.fahrenheit)
tomorrow.fahrenheit = 212
print(tomorrow.celsius)
let frozen = Temperature(celsius: -5)
// frozen.warm(by: 1) // error: frozen is a let constant, so the whole value is immutable
print(frozen.fahrenheit)
struct Stepper {
var steps = 0 {
didSet {
if steps >= 10_000 && oldValue < 10_000 {
print("Goal reached at \(steps) steps!")
}
}
}
}
var walk = Stepper()
for _ in 1...3 {
walk.steps += 4_000
}
print(walk.steps)21.0 25.0 77.0
100.0
23.0
Goal reached at 12000 steps!
12000Several ideas are packed in here:
var tomorrow = todaycopies the struct. Warmingtomorrowleavestodayat 21 degrees. This is value semantics: each variable owns its own value, like a number. If you writevar a = 5; var b = a; b += 1, nobody expectsato change, and with structs nobody has to.fahrenheitis a computed property with a getter and a setter. Setting it to 212 updatescelsiusto 100. Callers cannot tell whether a property is stored or computed, so you can change your mind later without breaking them.- Methods that change a struct's properties must be marked
mutating. That marker lets the compiler forbid calling them on aletconstant:frozenis completely immutable, all the way down. With a struct,letreally means constant. - A property observer (
didSet, orwillSet) runs code whenever a stored property changes; insidedidSet,oldValueis the previous value. Observers are good for keeping things in sync, such as updating a display, and bad for hiding important logic, since an assignment that looks innocent can do work.
You can write your own initializers too, including failable ones, init?, that return nil when the input makes no sense, and static members that belong to the type rather than to any one value:
struct Percentage {
let value: Int
init?(_ value: Int) {
guard (0...100).contains(value) else { return nil }
self.value = value
}
static let full = Percentage(100)!
}Now no code anywhere can create a Percentage of 140: the type itself guarantees its rule, so functions that receive one never need to check again. This is one of the most valuable habits in typed languages: validate once, at the boundary, and let the type carry the proof. (The ! on full is one of the rare acceptable force unwraps from the optionals lesson: the literal 100 is written in the source, so failure would be a programming error.) If you declare an initializer inside the struct, the memberwise one disappears; declare yours in an extension (next lesson) to keep both.
Classes and reference semantics
A class has properties, methods and initializers like a struct, but differs in three important ways: it has no memberwise initializer (you write init yourself, and must give every stored property a value before the object is used), it can inherit from another class, and it is a reference type.
final class Account {
let owner: String
private(set) var balance: Int // in cents
init(owner: String, balance: Int = 0) {
self.owner = owner
self.balance = balance
}
func deposit(_ cents: Int) {
balance += cents
}
}
struct Wallet {
var cash: Int
}
// Classes: assignment shares one object.
let mine = Account(owner: "Priya")
let shared = mine
shared.deposit(5_000)
print(mine.balance, shared.balance, mine === shared)
// Structs: assignment copies.
var w1 = Wallet(cash: 1_000)
var w2 = w1
w2.cash += 500
print(w1.cash, w2.cash)
// Inheritance and overriding.
class Vehicle {
let wheels: Int
init(wheels: Int) { self.wheels = wheels }
func describe() -> String { "a vehicle with \(wheels) wheels" }
}
class Bicycle: Vehicle {
init() { super.init(wheels: 2) }
override func describe() -> String { "a bicycle, " + super.describe() }
}
let fleet: [Vehicle] = [Vehicle(wheels: 4), Bicycle()]
for v in fleet {
print(v.describe())
}5000 5000 true
1000 1500
a vehicle with 4 wheels
a bicycle, a vehicle with 2 wheelslet shared = mine does not copy the account; it copies a reference to the one account object, so a deposit through either name is visible through both. The === operator asks "are these the same object?" (identity), which is different from ==, "are these equal values?". Notice too that mine is a let, yet its balance changed: for a class, let freezes the reference (you cannot point mine at another account) but not the object it refers to.
private(set) lets anyone read balance but only the class itself change it, so all changes go through deposit. final says no subclass may inherit from Account, which documents intent and lets the compiler call methods directly instead of looking them up at run time. Many Swift style guides make classes final unless they are designed for inheritance.
Bicycle inherits from Vehicle, calls the superclass initializer with super.init, and overrides describe(). Swift requires the override keyword, so you cannot override a method by accident or think you are overriding when a typo means you are not. When the loop calls describe() on each element of [Vehicle], the bicycle's version runs: dynamic dispatch, the heart of classic object-oriented programming.
Values, references and copy-on-write
Analogy, not a formal construction
A struct is like a printed document: hand someone a copy and they can scribble on it without changing yours. A class instance is like a shared online document: hand someone the link and every edit they make appears on your screen too. Both are useful. The danger is sending a link when the other person thought they had a copy.
Reference semantics causes a family of bugs that value semantics avoids. A function receives an array of accounts, sorts or edits one "for a moment", and some other part of the program sees the change. Two threads hold the same object and modify it at once. Code far away keeps a reference you forgot about. With value types, none of this can happen: if you have a value, it is yours, and it only changes when you change it. This makes value types easier to reason about, easier to test, and, as the concurrency lesson will show, safe to send between threads.
Doesn't copying cost time? For small structs (a few numbers), copying is cheaper than the bookkeeping a shared object needs. For large values, the standard library uses copy-on-write: an Array, Dictionary, Set or String keeps its elements in a heap buffer, and copying the value only copies a reference to that buffer. When one copy is about to be modified, it checks whether the buffer is shared; if so, it copies the buffer first, and only then writes. So var b = a is cheap, and the real copy happens at most once, at the first write, and only if both copies are still alive. Your own structs get this for free whenever their properties are standard collections.
Enums: one of several alternatives
An enum lists the possible cases of a value. In its simplest form, the cases are just names, but Swift's enums can do much more: have raw values, conform to protocols such as CaseIterable, have methods and computed properties, and, most powerfully, carry associated values that differ from case to case.
enum Direction: String, CaseIterable {
case north, east, south, west
var opposite: Direction {
switch self {
case .north: .south
case .south: .north
case .east: .west
case .west: .east
}
}
}
print(Direction.allCases.map(\.rawValue))
print(Direction.east.opposite, Direction(rawValue: "south") ?? .north, Direction(rawValue: "up") == nil)
enum Payment {
case cash
case card(last4: String)
case mobileMoney(provider: String, phone: String)
case voucher(code: String, cents: Int)
}
func receipt(for payment: Payment, total cents: Int) -> String {
switch payment {
case .cash:
return "Paid \(cents) cents in cash"
case .card(let last4):
return "Card ending \(last4) charged \(cents) cents"
case let .mobileMoney(provider, phone):
return "\(provider) payment from \(phone)"
case .voucher(let code, let value) where value >= cents:
return "Voucher \(code) covers it all"
case .voucher(let code, let value):
return "Voucher \(code) covers \(value); \(cents - value) cents still due"
}
}
let payments: [Payment] = [
.cash,
.card(last4: "4417"),
.mobileMoney(provider: "M-Pesa", phone: "+254 700 000 000"),
.voucher(code: "EID25", cents: 2_500),
.voucher(code: "SMALL", cents: 300),
]
for p in payments {
print(receipt(for: p, total: 1_200))
}
if case .card(let digits) = payments[1] {
print("Second payment used a card:", digits)
}["north", "east", "south", "west"]
west south true
Paid 1200 cents in cash
Card ending 4417 charged 1200 cents
M-Pesa payment from +254 700 000 000
Voucher EID25 covers it all
Voucher SMALL covers 300; 900 cents still due
Second payment used a card: 4417Direction has String raw values; when you do not give them, they default to the case names. Direction(rawValue:) is a failable initializer, returning nil for text that is not a case. CaseIterable makes the compiler generate allCases. map(\.rawValue) passes a key path where a function is expected, a shorthand for { $0.rawValue }. Inside a method, switch self handles each case, and because the type of the result is known, you can write .south rather than Direction.south.
Payment is where enums become a modelling tool. Each case carries exactly the data that makes sense for it: a card has its last four digits, mobile money has a provider and a phone number, cash has nothing. You cannot build a cash payment with a card number, or a card payment without one. Compare a class with optional properties last4, provider, phone, code, any combination of which might be set: every function would have to check for nonsense combinations. The enum makes them impossible to represent. In type theory, an enum like this is a sum type (a value is one alternative or another), while a struct is a product type (a value has one field and another).
The switch in receipt unpacks the associated values with let bindings and uses a where clause to split the voucher case in two. Add a fifth payment method and this switch stops compiling until you handle it, which is exactly what you want when money is involved. if case tests for one case when you care about no other.
Recursive enums
An enum case can contain a value of the same enum, if you mark it indirect (so Swift stores it in a separate allocation, otherwise the enum would contain itself and have infinite size). This is a natural way to represent trees:
// An arithmetic expression is a number, or an operation on two smaller expressions.
indirect enum Expr {
case number(Double)
case add(Expr, Expr)
case multiply(Expr, Expr)
case negate(Expr)
func evaluate() -> Double {
switch self {
case .number(let x): x
case .add(let a, let b): a.evaluate() + b.evaluate()
case .multiply(let a, let b): a.evaluate() * b.evaluate()
case .negate(let a): -a.evaluate()
}
}
var text: String {
switch self {
case .number(let x): "\(x)"
case .add(let a, let b): "(\(a.text) + \(b.text))"
case .multiply(let a, let b): "\(a.text) × \(b.text)"
case .negate(let a): "-\(a.text)"
}
}
}
// (2 + 3) × -4
let e = Expr.multiply(.add(.number(2), .number(3)), .negate(.number(4)))
print(e.text, "=", e.evaluate())(2.0 + 3.0) × -4.0 = -20.0Each function follows the shape of the data: one case per kind of node, calling itself on the children. Compilers, interpreters, document formats and JSON values are all written this way, in Swift and in every language with sum types.
Choosing between them
Experienced Swift developers ask a short series of questions:
- Is the value one of a fixed set of alternatives? Use an enum, with associated values if the alternatives carry different data. States of a screen (
loading,loaded(items),failed(error)), commands, tokens, results. - Otherwise, start with a struct. Data that is defined by its contents (a temperature, a date, an address, a configuration, a row from a file) is a value. Two structs with the same contents are interchangeable.
- Use a class when identity matters: when there is one thing that several parts of the program must share and see change, like a network connection, a cache, a document open in an editor, or a view controller in UIKit. Also use classes when a framework requires them, as many of Apple's older frameworks do, and when you need inheritance from an existing class.
Even then, a class often wraps value types inside: an Account object whose history is an array of Transaction structs. And Swift's protocols, the subject of the next lesson, give structs and enums most of the flexibility that inheritance gives classes, without the shared state.
Common misconceptions
Misconception
"Structs are for small things; real objects should be classes." Size is not the criterion. Swift's Array and String are structs and can hold gigabytes. The question is whether the thing has an identity that must be shared, and most data does not.
Misconception
"let makes any instance immutable." For a struct, yes, all the way down. For a class, let fixes only the reference; the object's var properties can still change through it, as mine.balance did. If you want an immutable class, make all its stored properties let.
Misconception
"Copying a struct with a big array inside copies the whole array." Not until someone writes to one of the copies while the other is still in use. Copy-on-write makes copies cheap; the cost is a check before each write, and a real copy only when sharing is detected.
Misconception
"An enum is just a set of named integer constants." That is what enums are in C. Swift's enums can carry different data in each case, have methods and conform to protocols. Optional itself is an enum.
Exercises
1. Structs, classes and enums
Warm-upComputationalWhat does this program print?
struct Counter { var n = 0 }
var a = Counter()
var b = a
b.n += 5
a.n += 1
print(a.n + b.n)
2. Structs, classes and enums
Warm-upComputationalNow Counter is a class. What does this program print?
final class CounterRef { var n = 0 }
let c = CounterRef()
let d = c
d.n += 5
c.n += 1
print(c.n + d.n)
3. Structs, classes and enums
CoreComputationalT is a struct with var celsius: Double, and K is a final class with var celsius = 0.0. Which of these two-line programs compiles?
4. Structs, classes and enums
CoreComputationalWhat does this program print?
enum Shape {
case circle(radius: Int)
case rectangle(width: Int, height: Int)
case square(side: Int)
}
func area(_ s: Shape) -> Int {
switch s {
case .circle(let r): 3 * r * r
case .rectangle(let w, let h): w * h
case .square(let side): side * side
}
}
print([Shape.circle(radius: 2), .rectangle(width: 3, height: 5), .square(side: 4)].map(area))
5. Structs, classes and enums
CoreComputationalWhat does this program print?
enum Planet: Int { case mercury = 1, venus, earth, mars }
print(Planet.mars.rawValue, Planet(rawValue: 2) == .venus)
6. Structs, classes and enums
StretchComputationalAssigning to a property inside its own didSet does not trigger the observer again. What does this program print?
struct Thermostat {
var target = 20 {
didSet {
if target > 26 { target = 26 }
}
}
}
var t = Thermostat()
t.target = 30
t.target -= 2
print(t.target)
7. Structs, classes and enums
CoreHumanA screen shows a network request that is idle, loading, finished with a list of items, or failed with an error message. Which model makes impossible states impossible to represent?
Further reading and resources
- The Swift Programming Language: Structures and Classes, Enumerations, Properties, Initialization, Inheritance
- Choosing Between Structures and ClassesApple's short guide, which recommends structures by default.
- WWDC 2015: Building Better Apps with Value Types in SwiftThe talk that made value semantics a core part of how Swift is taught.