Objects and classes
Reason about shared and copied state, then design classes that work together: an email server with clients, and cats that inherit and override.
This discussion goes with Lessons 12, 14, and 15. The recurring question: when two names refer to “the same thing”, is it one object or two copies?
Q1: What would Swift print?
What would Swift print?
struct PointValue {
var x = 0
}
class PointObject {
var x = 0
}
var values = [PointValue(), PointValue()]
let objects = [PointObject(), PointObject()]
var v = values[0]
let o = objects[0]
v.x = 1
o.x = 1
print(values[0].x, objects[0].x)Show answer and explanation
Answer0 1
v is a copy of the structure in the array, so changing it leaves the array
alone. o refers to the same object as objects[0], so the change shows.
What would Swift print?
class Node {
var value: Int
var next: Node?
init(_ value: Int, _ next: Node? = nil) {
self.value = value
self.next = next
}
}
let head = Node(1, Node(2))
let second = head.next!
second.value = 20
print(head.next!.value, head === second)Show answer and explanation
Answer20 false
second and head.next are the same object, so the change is visible
through head. But head itself is a different node, so === is false.
Q2: Email
Design three classes. An Email has a message, a sender name, and a
recipient name. A Server keeps registered clients by name and delivers an
email to its recipient’s inbox, dropping it silently if there is no such
client. A Client has a name and an inbox; creating one registers it with a
server, and compose(_:to:) sends an email through the server.
Show solution
class Email {
let message: String
let sender: String
let recipient: String
init(_ message: String, from sender: String, to recipient: String) {
self.message = message
self.sender = sender
self.recipient = recipient
}
}
class Server {
private var clients: [String: Client] = [:]
func register(_ client: Client) {
clients[client.name] = client
}
func send(_ email: Email) {
clients[email.recipient]?.receive(email)
}
}
class Client {
let name: String
private let server: Server
private(set) var inbox: [Email] = []
init(server: Server, name: String) {
self.server = server
self.name = name
server.register(self)
}
func compose(_ message: String, to recipient: String) {
server.send(Email(message, from: name, to: recipient))
}
func receive(_ email: Email) {
inbox.append(email)
}
}
let server = Server()
let ada = Client(server: server, name: "Ada")
let bo = Client(server: server, name: "Bo")
ada.compose("hi", to: "Bo")
ada.compose("anyone?", to: "Nobody")
assert(bo.inbox.map(\.message) == ["hi"])
assert(bo.inbox.first?.sender == "Ada")
assert(ada.inbox.isEmpty)These have to be classes: the server and the client must see the same
inbox. If Client were a structure, the server would deliver into its own
copy, and Bo’s inbox would stay empty. The client passes self to
register inside init, which is allowed once all its properties are set.
Q3: Noisy cats
A Cat has a name, an owner, and 9 lives. talk() returns
"<name> says meow!", and loseLife() takes one life, never going below
zero. A NoisyCat says everything twice: its talk() returns the normal
line repeated, separated by a space. Reuse the superclass’s method rather
than rewriting the text.
Show solution
class Cat {
let name: String
let owner: String
private(set) var lives = 9
init(name: String, owner: String) {
self.name = name
self.owner = owner
}
func talk() -> String {
"\(name) says meow!"
}
func loseLife() {
if lives > 0 {
lives -= 1
}
}
}
class NoisyCat: Cat {
override func talk() -> String {
let line = super.talk()
return line + " " + line
}
}
let kitty = NoisyCat(name: "Kitty", owner: "Ada")
assert(kitty.talk() == "Kitty says meow! Kitty says meow!")
for _ in 0..<12 {
kitty.loseLife()
}
assert(kitty.lives == 0)NoisyCat needs no initializer of its own: it adds no stored properties, so
it inherits Cat’s. super.talk() means that if cats ever change what they
say, noisy cats follow automatically.
Q4: Draw the objects
For this program, how many Counter objects exist when it prints, and what
does it print?
class Counter {
var count = 0
}
let a = Counter()
let b = a
var list = [a, Counter(), b]
list[1].count += 5
list[2].count += 1
print(a.count, list[1].count, list.count)
Show solution
Two objects exist. a, b, list[0], and list[2] all refer to the first
one; list[1] refers to the second. It prints 1 5 3: the first object was
incremented once through list[2], the second got 5, and the array holds
three references.
Drawing boxes for objects and arrows for references is how CS61A draws objects in environment diagrams, and it answers every “are these the same?” question at a glance.