After learning about structs over the past couple of days, we’re now looking at another kind of data structure that, while similar on the surface, is actually quite different.
We’re now on to a data structure called a class
. There are some key differences between a class
and a struct
, which are laid out in Day 12, and it seems that classes are mostly used for shuffling data around apps.
We learn about inheritance, using override
to customise subclasses, the necessity of init
, using deinit
and the complexities of variable and constant classes and their properties.
Checkpoint 7
For Checkpoint 7 we have to create a collection of classes which all inherit from one top level one and then have a variety of different properties and overriding functions. It’s not too challenging and Xcode’s code completion actually proves quite helpful in keeping me right here!
class Animal {
let legs: Int
init(legs: Int) {
self.legs = legs
}
}
class Dog: Animal {
func speak() {
print("Woof!")
}
init() {
super.init(legs: 4)
}
}
class Corgi: Dog {
override func speak() {
print("Bark!")
}
}
class Poodle: Dog {
override func speak() {
print("Grrr!")
}
}
class Cat: Animal {
var isTame: Bool
func speak() {
print("Meow!")
}
init(isTame: Bool) {
self.isTame = isTame
super.init(legs: 4)
}
}
class Persian: Cat {
override func speak() {
print("Prrrr!!")
}
init() {
super.init(isTame: true)
}
}
class Lion: Cat {
override func speak() {
print("Hisss!")
}
init() {
super.init(isTame: false)
}
}
(By the way, do lions ever hiss?)