Interface and implementation inheritance
One function for many list types: protocols as interfaces, default implementations and the static-dispatch trap in protocol extensions, static and dynamic types, class inheritance with override and super, initialization rules, type casting, and some versus any.
- Swift book
- Inheritance · Protocols · Type Casting · Initialization
We now have lists built from nodes and lists built from arrays. Suppose you want a function that finds the longest string in a list. Which list should it take? Writing it twice, once per type, works until there is a third list type, and then every such function needs a third copy. CS61B uses this problem to introduce inheritance. Swift gives you two kinds, and choosing between them is most of this lesson.
Interfaces: what, not how
The two lists share their operations, if not their storage. Write the operations down once, as a protocol:
protocol List61B<Element> {
associatedtype Element
var count: Int { get }
func get(_ index: Int) -> Element
mutating func addLast(_ item: Element)
}
CS61B calls List61B a hypernym of SLList and AList, and them its
hyponyms: every AList is a List61B. A function written against the
protocol works for all of them:
protocol List61B<Element> {
associatedtype Element
var count: Int { get }
func get(_ index: Int) -> Element
mutating func addLast(_ item: Element)
}
struct AList<Element>: List61B {
private var items: [Element] = []
var count: Int { items.count }
func get(_ index: Int) -> Element { items[index] }
mutating func addLast(_ item: Element) { items.append(item) }
}
final class SLList<Element>: List61B {
private final class Node {
let item: Element
var next: Node?
init(_ item: Element) { self.item = item }
}
private var first: Node?
private var last: Node?
private(set) var count = 0
func get(_ index: Int) -> Element {
var node = first!
for _ in 0..<index {
node = node.next!
}
return node.item
}
func addLast(_ item: Element) {
let node = Node(item)
if let last {
last.next = node
} else {
first = node
}
last = node
count += 1
}
}
func longest(_ list: some List61B<String>) -> String? {
guard list.count > 0 else {
return nil
}
var best = list.get(0)
for i in 1..<list.count where list.get(i).count > best.count {
best = list.get(i)
}
return best
}
var words = AList<String>()
let linked = SLList<String>()
for word in ["elk", "horse", "cat"] {
words.addLast(word)
linked.addLast(word)
}
print(longest(words)!, longest(linked)!) // horse horse
This is interface inheritance: AList and SLList inherit the promise
of what they can do, and each supplies its own way of doing it. some List61B<String> means “some particular type that conforms, with Element
equal to String”. The angle brackets work because Element is the
protocol’s primary associated type, declared in protocol List61B<Element>.
Default implementations
Protocols can also pass down code. An extension on the protocol provides a method to every conforming type at once. This is Swift’s form of what CS61B calls implementation inheritance, and what Java calls default methods:
extension List61B {
var last: Element? {
count > 0 ? get(count - 1) : nil
}
func printAll() {
for i in 0..<count {
print(get(i), terminator: " ")
}
print()
}
}
printAll works for any list, but it is written in terms of get, and for
SLList, get(i) walks i nodes. Printing a linked list this way walks
0 + 1 + 2 + … nodes: time proportional to the square of its length. SLList
can do better by walking once, so it should override the default with its
own version.
The static-dispatch trap
Here Swift has a rule that surprises everyone once. A method that is declared only in a protocol extension, and not in the protocol itself, is not a customization point. Which version runs is decided by the static type, the type the compiler sees, not the type of the value at run time:
protocol Greeter {
func greet() -> String // a requirement
}
extension Greeter {
func greet() -> String { "hello" }
func farewell() -> String { "goodbye" } // extension only
}
struct French: Greeter {
func greet() -> String { "bonjour" }
func farewell() -> String { "au revoir" }
}
let direct = French()
let viaProtocol: any Greeter = French()
print(direct.greet(), direct.farewell()) // bonjour au revoir
print(viaProtocol.greet(), viaProtocol.farewell()) // bonjour goodbye
greet is a requirement, so a call through the protocol finds French’s
version. farewell is not, so through the protocol the compiler only knows
about the extension’s version, and calls that. The fix is simple: if types
should be able to replace a default, declare it in the protocol as well
as implementing it in the extension. For List61B, that means adding
func printAll() to the protocol, so that SLList’s faster version is used
everywhere.
What would Swift print?
protocol Shape {
var area: Double { get }
}
extension Shape {
var name: String { "shape" }
}
struct Square: Shape {
var side: Double
var area: Double { side * side }
var name: String { "square" }
}
let shapes: [any Shape] = [Square(side: 2)]
print(shapes[0].area, shapes[0].name, Square(side: 2).name)Show answer and explanation
Answer4.0 shape square
area is a requirement, so the array’s element finds Square’s. name
exists only in the extension, so through any Shape the extension’s
version runs, even though the value is a Square. Called on a Square
directly, the compiler sees Square’s own.
Static and dynamic types
CS61B distinguishes a variable’s static type, the one written in the code and checked by the compiler, from its dynamic type, the type of the value it holds when the program runs:
let list: any List61B<String> = SLList<String>()
// static type: any List61B<String> dynamic type: SLList<String>
The rules that follow are the same in Java and Swift:
- The compiler only lets you call what the static type offers.
listhas nofirstproperty here, even though anSLListwould. - Calls to overridable methods, class methods and protocol requirements, go to the dynamic type’s version. This is dynamic dispatch.
- Overloads (functions with the same name and different parameter types) are chosen by the static type, at compile time. So are default arguments, as Ants found, and extension-only protocol methods, as above.
type(of:) reports a value’s dynamic type at run time:
class Animal {
func sound() -> String { "..." }
}
final class Dog: Animal {
override func sound() -> String { "woof" }
}
func describe(_ animal: Animal) -> String { "an animal" }
func describe(_ dog: Dog) -> String { "a dog" }
let pet: Animal = Dog()
print(pet.sound(), describe(pet), type(of: pet)) // woof an animal Dog
pet.sound() is dispatched dynamically and barks. describe(pet) is an
overload chosen at compile time from pet’s static type, Animal.
Class inheritance
Protocols pass down interfaces and default code. Classes can also inherit stored state: a subclass has every property and method of its superclass, and can add more or override methods. CS61B’s example is a list that rotates:
class SLList<Element> {
final class Node {
let item: Element
var next: Node?
init(_ item: Element, _ next: Node?) {
self.item = item
self.next = next
}
}
var first: Node?
var count = 0
func addFirst(_ item: Element) {
first = Node(item, first)
count += 1
}
func removeLast() -> Element? {
guard let head = first else { return nil }
count -= 1
guard head.next != nil else {
first = nil
return head.item
}
var node = head
while node.next!.next != nil {
node = node.next!
}
defer { node.next = nil }
return node.next!.item
}
var items: [Element] {
var result: [Element] = []
var node = first
while let current = node {
result.append(current.item)
node = current.next
}
return result
}
}
final class RotatingSLList<Element>: SLList<Element> {
/// Moves the last item to the front.
func rotateRight() {
if let item = removeLast() {
addFirst(item)
}
}
}
final class VengefulSLList<Element>: SLList<Element> {
private(set) var removed: [Element] = []
override func removeLast() -> Element? {
let item = super.removeLast()
if let item {
removed.append(item)
}
return item
}
}
let rotating = RotatingSLList<Int>()
let vengeful = VengefulSLList<Int>()
for n in [3, 2, 1] {
rotating.addFirst(n)
vengeful.addFirst(n)
}
rotating.rotateRight()
_ = vengeful.removeLast()
_ = vengeful.removeLast()
print(rotating.items, vengeful.items, vengeful.removed) // [3, 1, 2] [1] [3, 2]
RotatingSLListadds a method, written entirely with inherited ones.VengefulSLListoverridesremoveLast, markedoverrideso that nobody overrides a method by accident, and calls the original withsuper.removeLast().SLListis notfinal, so it can be subclassed; the node class isfinal, since nothing should subclass it. The node andfirstare no longerprivate, because subclasses in other files could not see private members; Swift has no Java-styleprotected.
Initializers
Swift is strict about initializing a subclass, because it must never be possible to use a property before it has a value. The Swift book’s chapter on initialization spells out the rules; the core of them is two-phase initialization:
- A subclass’s initializer first gives values to its own stored
properties, then calls
super.init(…)to let the superclass set up its part. - Only after
super.initreturns may it call methods or useselffreely.
class Account {
let owner: String
var balance: Int
init(owner: String, balance: Int) {
self.owner = owner
self.balance = balance
}
convenience init(owner: String) {
self.init(owner: owner, balance: 0)
}
}
final class SavingsAccount: Account {
let rate: Double
init(owner: String, balance: Int, rate: Double) {
self.rate = rate // phase 1: own properties
super.init(owner: owner, balance: balance) // then the superclass
self.balance += 1 // phase 2: self is ready
}
}
let savings = SavingsAccount(owner: "Ada", balance: 100, rate: 0.02)
print(savings.owner, savings.balance, savings.rate) // Ada 101 0.02
A designated initializer, like init(owner:balance:), fully initializes
the class. A convenience initializer must call another initializer of
the same class. Subclasses do not inherit initializers automatically when
they add stored properties without defaults, which is why
SavingsAccount(owner: "Ada") does not exist.
When implementation inheritance goes wrong
CS61B warns that implementation inheritance breaks encapsulation: a subclass depends on how its superclass is written, not just what it does.
What would Swift print?
class Dog {
func bark() -> String { "bark" }
func barkMany(_ n: Int) -> String {
(0..<n).map { _ in bark() }.joined(separator: " ")
}
}
final class VerboseDog: Dog {
override func bark() -> String {
barkMany(1)
}
}
print(VerboseDog().bark())Show answer and explanation
AnswerError
VerboseDog.bark calls barkMany, which the superclass happens to write
using bark, which is dispatched dynamically back to VerboseDog.bark. The
calls go around forever, and the program crashes when the stack runs out.
VerboseDog looked correct; the bug is in a detail of Dog it never saw.
This is why Swift code prefers protocols and composition, a type that
has another type as a property, over deep class hierarchies, and why
Swift’s value types cannot be subclassed at all. Mark classes final unless
subclassing is part of their design.
Type casting
Sometimes code needs to ask about a value’s dynamic type. The Swift book’s chapter on type casting describes four operators:
istests:pet is Dogistrueorfalse.as?tries to convert, giving an optional:pet as? Dog.as!converts or crashes; use it only when a failure would be a bug.asconverts where success is guaranteed, such asDog()toAnimal.
Casts also work as patterns in a switch:
let things: [Any] = [3, "three", 3.0, [3], true]
for thing in things {
switch thing {
case let n as Int: print("Int", n)
case let s as String: print("String", s)
case is Double: print("a Double")
default: print("something else")
}
}
// Int 3
// String three
// a Double
// something else
// something else
Code full of casts is usually a sign that a protocol requirement is missing.
CS61B’s maxDog function casts Objects to Dogs because Java code once had
no better option; with generics and protocols, the type checker knows the
types, and no cast is needed.
Function objects
Before Java had lambdas, CS61B passed functions around as objects that implement a one-method interface. Swift has function types (Lesson 4), but the object version is still useful when a function needs state or several related methods:
protocol IntUnaryFunction {
func apply(_ x: Int) -> Int
}
struct TenX: IntUnaryFunction {
func apply(_ x: Int) -> Int { 10 * x }
}
func doTwice(_ f: some IntUnaryFunction, _ x: Int) -> Int {
f.apply(f.apply(x))
}
func doTwice(_ f: (Int) -> Int, _ x: Int) -> Int {
f(f(x))
}
print(doTwice(TenX(), 2), doTwice({ 10 * $0 }, 2)) // 200 200
some or any
The two ways of writing “a list of strings” are different mechanisms:
some List61B<String>is generic: each call works with one specific type, known to the compiler, which can specialize the code for it.any List61B<String>is an existential: a box that can hold a value of any conforming type, decided at run time. It is needed when values of different types must live together, such as[any List61B<String>], and costs a little extra for the indirection.
Prefer some (or a named generic parameter) by default, and use any when
you really need the mix. Lesson 16 used both; now the reason is visible.
Put the lines in order
Put the lines in order so the program prints woof.
}let pet: any Animal = Dog()}protocol Animal {print(pet.sound())func sound() -> Stringstruct Dog: Animal {func sound() -> String { "woof" }
Show the correct program
protocol Animal {
func sound() -> String
}
struct Dog: Animal {
func sound() -> String { "woof" }
}
let pet: any Animal = Dog()
print(pet.sound())Lab 30: Inheritance
Q0: What would Swift print?
What would Swift print?
class Base {
func name() -> String { "base" }
func describe() -> String { "I am " + name() }
}
final class Derived: Base {
override func name() -> String { "derived" }
}
let b: Base = Derived()
print(b.describe())Show answer and explanation
AnswerI am derived
describe is inherited unchanged, but the name() it calls is dispatched
dynamically, and the value is a Derived. This is the helpful side of the
same mechanism that made VerboseDog crash.
What would Swift print?
func label(_ x: Any) -> String { "any" }
func label(_ x: Int) -> String { "int" }
let n = 5
let boxed: Any = n
print(label(n), label(boxed), boxed is Int)Show answer and explanation
Answerint any true
Overloads are chosen by static type: n is an Int, so label(n) is
"int"; boxed is statically Any, so label(boxed) is "any", even
though its dynamic type is Int, as is confirms.
Q1: A protocol with defaults
Write List61B with requirements count, get(_:), addLast(_:), and
printAll(), and a protocol extension that implements last, isEmpty,
and a default printAll() using get. Make SLList override printAll()
with a version that walks the nodes once, and show that the override is used
when the list is passed as any List61B<Int>.
Show solution
protocol List61B<Element> {
associatedtype Element
var count: Int { get }
func get(_ index: Int) -> Element
mutating func addLast(_ item: Element)
func printAll() -> String // a requirement, so it can be overridden
}
extension List61B {
var isEmpty: Bool { count == 0 }
var last: Element? { isEmpty ? nil : get(count - 1) }
func printAll() -> String {
(0..<count).map { "\(get($0))" }.joined(separator: " ")
}
}
var getCalls = 0
final class SLList<Element>: List61B {
private final class Node {
let item: Element
var next: Node?
init(_ item: Element) { self.item = item }
}
private var first: Node?
private var tail: Node?
private(set) var count = 0
func get(_ index: Int) -> Element {
getCalls += 1
var node = first!
for _ in 0..<index {
node = node.next!
}
return node.item
}
func addLast(_ item: Element) {
let node = Node(item)
if let tail {
tail.next = node
} else {
first = node
}
tail = node
count += 1
}
func printAll() -> String {
var parts: [String] = []
var node = first
while let current = node {
parts.append("\(current.item)")
node = current.next
}
return parts.joined(separator: " ")
}
}
let list = SLList<Int>()
for n in 1...4 {
list.addLast(n)
}
let general: any List61B<Int> = list
assert(general.printAll() == "1 2 3 4")
assert(getCalls == 0) // the node-walking override ran
assert(general.last == 4 && getCalls == 1)Returning a string instead of printing makes the method testable. last
and isEmpty stay extension-only, since there is no faster way to write them
for this list; printAll is a requirement, and that is what lets the call
through any List61B<Int> find the override.
Q2: A list that remembers its size history
Subclass the lesson’s SLList as CountingSLList, which overrides
addFirst and removeLast to keep track of the largest size the list has
ever had, calling the superclass versions to do the work.
Show solution
class SLList<Element> {
final class Node {
let item: Element
var next: Node?
init(_ item: Element, _ next: Node?) {
self.item = item
self.next = next
}
}
var first: Node?
var count = 0
func addFirst(_ item: Element) {
first = Node(item, first)
count += 1
}
func removeLast() -> Element? {
guard let head = first else { return nil }
count -= 1
guard head.next != nil else {
first = nil
return head.item
}
var node = head
while node.next!.next != nil {
node = node.next!
}
defer { node.next = nil }
return node.next!.item
}
}
final class CountingSLList<Element>: SLList<Element> {
private(set) var largest = 0
override func addFirst(_ item: Element) {
super.addFirst(item)
largest = max(largest, count)
}
override func removeLast() -> Element? {
super.removeLast()
}
}
let list = CountingSLList<Character>()
for c in "swift" {
list.addFirst(c)
}
_ = list.removeLast()
_ = list.removeLast()
list.addFirst("!")
assert(list.count == 4 && list.largest == 5)Only addFirst can make the list bigger, so only it updates largest. The
removeLast override adds nothing and could be deleted; it is there to show
that an override may simply delegate. Checking count after
super.addFirst relies on the superclass having updated it, exactly the kind
of dependence on implementation details this lesson warned about.
Q3: Initializers
Write a class Shape with a name, and subclasses Circle (with a
radius) and Square (with a side), each with an area computed property
overriding Shape’s. Give Circle a convenience initializer
init(diameter:). Then compute the total area of a [Shape].
Show solution
class Shape {
let name: String
init(name: String) {
self.name = name
}
var area: Double { 0 }
}
final class Circle: Shape {
let radius: Double
init(radius: Double) {
self.radius = radius
super.init(name: "circle")
}
convenience init(diameter: Double) {
self.init(radius: diameter / 2)
}
override var area: Double { Double.pi * radius * radius }
}
final class Square: Shape {
let side: Double
init(side: Double) {
self.side = side
super.init(name: "square")
}
override var area: Double { side * side }
}
let shapes: [Shape] = [Circle(diameter: 2), Square(side: 3), Square(side: 1)]
let total = shapes.map(\.area).reduce(0, +)
assert(abs(total - (Double.pi + 10)) < 1e-9)
assert(shapes.map(\.name) == ["circle", "square", "square"])Each subclass initializes its own property before calling super.init, and
the convenience initializer delegates to the designated one in its own class.
Computed properties are overridden just like methods.
Q4: Sorting out a mixed bag
Write summarize(_:), which takes an [Any] and returns the sum of the
integers, the total length of the strings, and how many other values there
were, using one switch with cast patterns.
Show solution
func summarize(_ values: [Any]) -> (sum: Int, letters: Int, other: Int) {
var result = (sum: 0, letters: 0, other: 0)
for value in values {
switch value {
case let n as Int: result.sum += n
case let s as String: result.letters += s.count
default: result.other += 1
}
}
return result
}
let summary = summarize([1, "two", 3, 4.0, "five", [6], 7])
assert(summary.sum == 11 && summary.letters == 7 && summary.other == 2)4.0 is a Double, not an Int, so it falls to default: casting never
converts numbers between types. If most code looked like this, a protocol
that all the values conformed to would be the better design.
Q5: some and any
Write total(_:), which adds up a list of Ints given as some List61B<Int>,
and grandTotal(_:), which adds up an array holding both AList<Int>s and
SLList<Int>s. Explain why the second needs any.
Show solution
protocol List61B<Element> {
associatedtype Element
var count: Int { get }
func get(_ index: Int) -> Element
}
struct AList<Element>: List61B {
var items: [Element]
var count: Int { items.count }
func get(_ index: Int) -> Element { items[index] }
}
struct Repeated<Element>: List61B {
let item: Element
let count: Int
func get(_ index: Int) -> Element { item }
}
func total(_ list: some List61B<Int>) -> Int {
(0..<list.count).reduce(0) { $0 + list.get($1) }
}
func grandTotal(_ lists: [any List61B<Int>]) -> Int {
lists.reduce(0) { $0 + total($1) }
}
assert(total(AList(items: [1, 2, 3])) == 6)
assert(grandTotal([AList(items: [1, 2, 3]), Repeated(item: 10, count: 4)]) == 46)An array holds values of one type. [some List61B<Int>] would mean “an array
of one particular list type”, so it could not hold both kinds. any puts each
value in a box of the single type any List61B<Int>, which is what makes the
mix possible. Passing a boxed value to total, which takes some, works
because Swift opens the box and calls the generic function with the value’s
real type.
Q6 (optional): Fixing the fragile base
Rewrite the Dog example so that VerboseDog cannot cause infinite
recursion, in two ways: once by changing Dog so that barkMany does not
depend on an overridable method, and once with composition instead of
inheritance.
Show solution
class Dog {
func bark() -> String { "bark" }
final func barkMany(_ n: Int) -> String {
Array(repeating: "bark", count: n).joined(separator: " ")
}
}
final class VerboseDog: Dog {
override func bark() -> String { barkMany(1) + "!" }
}
protocol Barker {
func bark() -> String
}
struct PlainBarker: Barker {
func bark() -> String { "bark" }
}
struct Loud: Barker {
let base: any Barker
func bark() -> String { base.bark().uppercased() + "!" }
}
assert(VerboseDog().bark() == "bark!")
assert(Loud(base: Loud(base: PlainBarker())).bark() == "BARK!!")The first fix makes barkMany final and independent of bark, so no
subclass can loop back into it. The second has no inheritance at all: Loud
wraps any Barker and adds to its behavior through its public interface
only, so it cannot depend on how the wrapped value is implemented. Wrappers
can even be stacked.
What’s next
Next lesson: the standard protocols that make a type feel built in, so that
your lists work with for–in, ==, and sorted().