References, identity, and memory
The start of the data structures half: boxes and arrows, the golden rule of assignment, parameter passing, identity versus equality, type members, and how ARC decides when an object dies.
- CS61B
- Intro to Java · Defining and Using Classes · Lists, Arrays, Maps, References · Textbook Ch. 1, Ch. 2, Ch. 3
- Documentation
- ObjectIdentifier · AnyObject
Units 1 to 3 followed CS61A: how to build abstractions from functions and data, and how a language runs them. This lesson starts the second half of the tutorial, which follows CS61B, Berkeley’s data structures course. The questions change. Instead of “how do I express this idea?”, they become “how is this collection actually stored, what does each operation cost, and how do I build one myself?”
CS61B begins by teaching Java to students who know Python. You already know Swift, so this lesson keeps the part of those first lectures that matters most for building data structures, and that trips up programmers in every language: what a variable actually holds.
Boxes and arrows
Think of every variable as a box. What goes in the box depends on the kind of type:
- For a value type (
Int,Double,Bool,String, arrays, dictionaries, and everystructandenum), the box holds the value itself. - For a reference type (every
class), the box holds an arrow: a reference to an object that lives somewhere else in memory.
Here is the same idea as a structure and as a class. CS61B uses walruses for this example, and so will we:
struct WalrusValue {
var weight: Int
}
final class Walrus {
var weight: Int
init(weight: Int) {
self.weight = weight
}
}
var a = WalrusValue(weight: 1000)
var b = a
b.weight = 5
let c = Walrus(weight: 1000)
let d = c
d.weight = 5
print(a.weight, c.weight) // 1000 5
Drawn as boxes and arrows:
a ┌──────────────┐ c ┌───┐ ┌──────────────┐
│ weight: 1000 │ │ ●─┼──────▶│ weight: 5 │
└──────────────┘ └───┘ ┌──▶└──────────────┘
b ┌──────────────┐ d ┌───┐ │
│ weight: 5 │ │ ●─┼───┘
└──────────────┘ └───┘
a and b are two separate walruses. c and d are two arrows to one
walrus, so a change made through d is seen through c. Note that c and
d are let constants and the change still worked: let fixes the arrow,
not the object it points to.
The golden rule of assignment
CS61B calls this the golden rule of equals, and it holds in Swift too:
b = acopies whatever is ina’s box intob’s box.
For a value type, that is the value. For a reference type, that is the arrow, so afterwards both boxes point at the same object. There is no special case to remember: assignment always copies the box. What differs is only what the box contains.
What would Swift print?
final class Counter {
var count = 0
}
struct Tally {
var count = 0
}
var x = Counter()
var y = x
y.count += 1
y = Counter()
y.count += 10
var p = Tally()
var q = p
q.count += 1
print(x.count, y.count, p.count, q.count)Show answer and explanation
Answer1 10 0 1
y = x copies the arrow, so the first increment changes the counter x
points to. y = Counter() then points y at a new counter; x is not
affected, and still sees 1. The Tally values are independent from the start.
Passing arguments
Calling a function assigns each argument to its parameter, so the golden rule applies there too. A function receives a copy of the box:
final class Walrus {
var weight: Int
init(weight: Int) {
self.weight = weight
}
}
func feed(_ walrus: Walrus) {
walrus.weight += 100 // follows the arrow: the caller sees this
}
func replace(_ walrus: Walrus) {
var walrus = walrus // a local copy of the arrow
walrus = Walrus(weight: 0) // points the copy elsewhere
walrus.weight = 1
}
let w = Walrus(weight: 3500)
feed(w)
replace(w)
print(w.weight) // 3600
feed follows the arrow and changes the shared walrus. replace only
changes where its own copy of the arrow points, which the caller cannot see.
To let a function change the caller’s box itself, Swift makes you say so
with inout and &, as in Lesson 13. Nothing is ever passed “by
reference” by accident.
Identity and equality
Two questions look alike but are different:
- Equality,
==: do these two things have the same value? A type decides what that means by conforming toEquatable. - Identity,
===: are these two references arrows to the very same object? Only reference types have identity.
final class Walrus: Equatable {
var weight: Int
init(weight: Int) {
self.weight = weight
}
static func == (lhs: Walrus, rhs: Walrus) -> Bool {
lhs.weight == rhs.weight
}
}
let a = Walrus(weight: 100)
let b = Walrus(weight: 100)
let c = a
print(a == b, a === b, a === c) // true false true
a and b are equal but not identical: two walruses that happen to weigh
the same. Java’s == is identity for objects, which is the source of one of
CS61B’s most common bugs; in Swift, === makes identity a separate, visible
question. ObjectIdentifier(a) turns an object’s identity into a Hashable
value, which is how you put objects into a Set by identity rather than by
value.
Type members
Everything above belongs to one instance: each walrus has its own weight.
Properties and methods marked static belong to the type instead, and
exist once however many instances there are. CS61B’s example is a dog
class that knows its species’ scientific name and can compare two dogs:
struct Dog {
static let binomen = "Canis familiaris"
static private(set) var created = 0
let name: String
let size: Int
init(name: String, size: Int) {
self.name = name
self.size = size
Dog.created += 1
}
func noise() -> String {
size < 10 ? "yip" : size < 30 ? "bark" : "woof"
}
static func larger(_ a: Dog, _ b: Dog) -> Dog {
a.size >= b.size ? a : b
}
}
let dogs = [Dog(name: "Maya", size: 5), Dog(name: "Rex", size: 40), Dog(name: "Kuma", size: 25)]
let biggest = dogs.reduce(dogs[0], Dog.larger)
print(Dog.binomen, Dog.created, biggest.name, biggest.noise())
// Canis familiaris 3 Rex woof
noise() is an instance method, because it depends on one dog’s size.
larger needs no particular dog to call it on, so it is static, and is
called on the type: Dog.larger. A static stored property like created
is a single shared box, one of the few places where value types share
state. Classes can also write class func or class var for type members
that subclasses may override, as Ants did.
Arrays of objects
An array is a value type, but an array of objects holds arrows. That combination causes a classic bug:
What would Swift print?
final class Cell {
var alive = false
}
var grid = [Cell](repeating: Cell(), count: 3)
grid[0].alive = true
print(grid.map(\.alive))
var fresh = (0..<3).map { _ in Cell() }
fresh[0].alive = true
print(fresh.map(\.alive))Show answer and explanation
Answer[true, true, true]
[true, false, false]
Cell() is evaluated once, and repeating: copies that arrow three
times: one cell, three arrows. The map version calls Cell() once per
element, making three cells. With a value type, both versions would give
[true, false, false].
Copying an array of objects copies the arrows, not the objects. That is a
shallow copy. When the elements must be independent too, a deep copy
makes new objects: walruses.map { Walrus(weight: $0.weight) }.
Where objects live, and when they die
Every class instance takes memory, and something must decide when to give it
back. Java uses a garbage collector, which periodically searches for objects
nothing points to. Swift uses automatic reference counting (ARC): each
object keeps a count of the strong references pointing at it, and the moment
the count reaches zero, the object is destroyed. Just before that, its
deinit runs:
final class Walrus {
let name: String
init(name: String) {
self.name = name
print("hello,", name)
}
deinit {
print("goodbye,", name)
}
}
var first: Walrus? = Walrus(name: "Wally")
var second = first // two arrows: the count is 2
first = nil // the count is 1
print("still here")
second = nil // the count is 0: Wally is destroyed
print("done")
// hello, Wally
// still here
// goodbye, Wally
// done
The moment is predictable, which is useful: a deinit can close a file or
release a lock exactly when the object is no longer needed. Swift promises
that an object lives at least until the last place it is used, so do not
rely on the exact line where a local variable’s object dies; setting an
optional to nil, as above, is the reliable way to show it.
What would Swift print?
final class Node {
let label: String
var next: Node?
init(_ label: String) {
self.label = label
}
deinit {
print("freed", label)
}
}
var head: Node? = Node("a")
head!.next = Node("b")
head = nil
print("end")Show answer and explanation
Answerfreed a
freed b
end
Setting head to nil drops the only reference to a, so a is freed.
Freeing a releases its next arrow, the only reference to b, so b is
freed right after. Freeing a linked structure frees everything reachable only
through it, one step at a time.
Cycles
Reference counting has one weakness. If two objects point at each other, each
keeps the other’s count above zero, and neither is ever freed, even after the
rest of the program has forgotten them. That is a memory leak. Lesson 15
met this with weak; in counting terms:
- A strong reference, the default, adds 1 to the count.
- A
weakreference does not count. It must be an optionalvar, and becomesnilautomatically when its object is destroyed. - An
unownedreference does not count either, and is not optional. Use it only when the object is guaranteed to outlive the reference; reading it after the object is gone crashes.
final class Person {
let name: String
var apartment: Apartment?
init(name: String) { self.name = name }
deinit { print(name, "freed") }
}
final class Apartment {
let unit: String
weak var tenant: Person? // weak: the apartment does not own its tenant
init(unit: String) { self.unit = unit }
deinit { print(unit, "freed") }
}
var ada: Person? = Person(name: "Ada")
var flat: Apartment? = Apartment(unit: "4A")
ada!.apartment = flat
flat!.tenant = ada
ada = nil
flat = nil
// Ada freed
// 4A freed
Without weak, both deinits would stay silent: each object would hold the
other alive forever. The rule of thumb is to decide which object owns
which. Owners hold strong references; back-references, like a child’s link
to its parent or a tenant’s apartment, are weak or unowned. Lesson 29’s
doubly linked lists are built on exactly this decision.
Put the lines in order
Put the lines in order so the program prints 2 1.
self.value = valuelet copy = Box(original.value)}let original = Box(1)print(original.value, copy.value)var value: Intlet alias = original}init(_ value: Int) {alias.value = 2final class Box {
Show the correct program
final class Box {
var value: Int
init(_ value: Int) {
self.value = value
}
}
let original = Box(1)
let alias = original
let copy = Box(original.value)
alias.value = 2
print(original.value, copy.value)Lab 24: References
Q0: What would Swift print?
What would Swift print?
final class Walrus {
var weight: Int
init(_ weight: Int) {
self.weight = weight
}
}
func swap(_ a: Walrus, _ b: Walrus) {
let temp = a.weight
a.weight = b.weight
b.weight = temp
}
let x = Walrus(1)
let y = Walrus(2)
swap(x, y)
swap(x, x)
print(x.weight, y.weight)Show answer and explanation
Answer2 1
The first call follows both arrows and exchanges the weights. The second
passes the same walrus twice: temp is 2, and both assignments write 2 to
the one walrus, so nothing changes.
What would Swift print?
var scores = ["ada": [1, 2]]
var copy = scores
copy["ada"]!.append(3)
scores["ada"]![0] = 10
print(scores["ada"]!, copy["ada"]!)Show answer and explanation
Answer[10, 2] [1, 2, 3]
A dictionary of arrays is values all the way down. copy is independent,
and changing an element through scores["ada"]! changes the array inside
the dictionary in place.
Q1: Boxes and arrows
Draw the boxes and arrows after this code runs, then predict what it prints.
final class Node {
var value: Int
var next: Node?
init(_ value: Int, _ next: Node? = nil) {
self.value = value
self.next = next
}
}
let c = Node(3)
let b = Node(2, c)
let a = Node(1, b)
let d = a.next
d!.value = 20
a.next = c
print(a.value, a.next!.value, b.value, d === b)
Show solution
It prints 1 3 20 true.
a ──▶ [1 | ●]──┐ (a.next now skips b)
▼
d ──▶ [20 | ●]──▶ [3 | nil] ◀── c
▲
b ────┘d = a.next copies the arrow to the node that b also points to, so
d!.value = 20 changes b’s node. Then a.next = c redirects a’s arrow
to the last node. b’s node still exists, because b and d point to it,
and it still points to c’s node.
Q2: Dogs
Extend Dog with a static method largest(_:) that returns the largest dog
in an array (or nil for an empty array), and an instance method
isLarger(than:). Keep a static count of how many dogs have been created,
and check it.
Show solution
struct Dog {
static private(set) var created = 0
let name: String
let size: Int
init(name: String, size: Int) {
self.name = name
self.size = size
Dog.created += 1
}
func isLarger(than other: Dog) -> Bool {
size > other.size
}
static func largest(_ dogs: [Dog]) -> Dog? {
dogs.max { $1.isLarger(than: $0) }
}
}
let pack = [Dog(name: "Maya", size: 5), Dog(name: "Rex", size: 40), Dog(name: "Kuma", size: 25)]
assert(Dog.largest(pack)?.name == "Rex")
assert(Dog.largest([]) == nil)
assert(pack[2].isLarger(than: pack[0]))
assert(Dog.created == 3)max(by:) takes an “is less than” function, so it is given “the second is
larger than the first”. Reusing isLarger(than:) keeps the comparison in
one place. Copying a Dog value does not call init, so created counts
dogs created, not copies.
Q3: Deep copies
A Pack of walruses is a class holding an array of Walrus objects. Write
shallowCopy() and deepCopy(), and show the difference with a test.
Show solution
final class Walrus {
var weight: Int
init(weight: Int) {
self.weight = weight
}
}
final class Pack {
var members: [Walrus]
init(_ members: [Walrus]) {
self.members = members
}
func shallowCopy() -> Pack {
Pack(members)
}
func deepCopy() -> Pack {
Pack(members.map { Walrus(weight: $0.weight) })
}
}
let pack = Pack([Walrus(weight: 100), Walrus(weight: 200)])
let shallow = pack.shallowCopy()
let deep = pack.deepCopy()
pack.members[0].weight = 999
pack.members.append(Walrus(weight: 1))
assert(shallow.members.map(\.weight) == [999, 200]) // shares the walruses
assert(deep.members.map(\.weight) == [100, 200]) // its own walruses
assert(shallow.members.count == 2) // but its own arrayThe shallow copy has its own array, since arrays are values, so the new
walrus appended to pack does not appear in it. The arrows inside it still
lead to the original walruses.
Q4: Counting live objects
Write a class Tracked that keeps a static count of how many instances are
currently alive: increase it in init, decrease it in deinit. Use it to
show that a two-object cycle leaks, and that making one reference weak
fixes it.
Show solution
final class Tracked {
static private(set) var alive = 0
var next: Tracked?
weak var back: Tracked?
init() {
Tracked.alive += 1
}
deinit {
Tracked.alive -= 1
}
}
var a: Tracked? = Tracked()
var b: Tracked? = Tracked()
a!.next = b
b!.next = a // a cycle of strong references
a = nil
b = nil
assert(Tracked.alive == 2) // leaked: nothing can reach them, and they are never freed
var c: Tracked? = Tracked()
var d: Tracked? = Tracked()
c!.next = d
d!.back = c // the back-reference does not count
c = nil
d = nil
assert(Tracked.alive == 2) // only the two leaked objects remainAfter the first part, the program has no way to reach the two leaked objects,
and ARC will never free them. The second pair is freed as soon as the
variables are cleared: c has no strong references once c is nil, and
freeing it releases the only strong reference to d.
Q5: Unique by identity
Write uniqueObjects(_:), which removes repeated references from an
array of Walrus objects, keeping the first occurrence of each object, even
when different objects are equal in weight. Use ObjectIdentifier.
Show solution
final class Walrus {
var weight: Int
init(weight: Int) {
self.weight = weight
}
}
func uniqueObjects(_ walruses: [Walrus]) -> [Walrus] {
var seen: Set<ObjectIdentifier> = []
return walruses.filter { seen.insert(ObjectIdentifier($0)).inserted }
}
let a = Walrus(weight: 100)
let b = Walrus(weight: 100)
let result = uniqueObjects([a, b, a, a, b])
assert(result.count == 2)
assert(result[0] === a && result[1] === b)Set.insert returns whether the element was new, so the filter keeps
exactly the first occurrence of each identity. a and b weigh the same but
are different objects, so both are kept.
Q6 (optional): A shared bank, and a private one
Write a class SharedAccount and a structure PrivateAccount, each with a
balance and a deposit(_:) method. Write one generic function
depositTwice(_:) that works for both through a protocol, and explain why
it needs inout for the structure but not for the class.
Show solution
protocol Account {
var balance: Int { get }
mutating func deposit(_ amount: Int)
}
final class SharedAccount: Account {
private(set) var balance = 0
func deposit(_ amount: Int) {
balance += amount
}
}
struct PrivateAccount: Account {
private(set) var balance = 0
mutating func deposit(_ amount: Int) {
balance += amount
}
}
func depositTwice<A: Account>(_ account: inout A) {
account.deposit(10)
account.deposit(10)
}
var shared = SharedAccount()
let alias = shared
depositTwice(&shared)
assert(alias.balance == 20) // the same object
var mine = PrivateAccount()
let snapshot = mine
depositTwice(&mine)
assert(mine.balance == 20 && snapshot.balance == 0)A mutating requirement lets a structure change itself, so a generic
function has to take the value inout to change the caller’s copy. A class
satisfies the requirement with an ordinary method, since changing an object
never changes the arrow to it. Generic code written against the protocol
works for both kinds of type, but the difference in what = copies still
shows through: alias sees the deposits, snapshot does not.
What’s next
The CS61B projects draw on screen, and the first one is a falling-sand physics sandbox. Next lesson: drawing with SwiftUI.