Hi, I just completed this checkpoint before watching Paul's hints. After seeing the hints, I realised I maybe should have used override func...
in the child classes, but the way I did it still feels OK.
My reasoning: I thought it would be good for child classes (breeds of Dog and Cat) to pass what they say up to the parent classes (Dog and Cat), and for the parent classes to have the only speak()
function, rather than overriding the function and so having many more instances of it...
So for dogs...
class Animal {
var legs: Int
init(legs: Int) {
self.legs = legs
}
}
class Dog: Animal {
var iSay: String
func speak() {
print("I say \(iSay)")
}
init(iSay: String) {
self.iSay = iSay
super.init(legs: 4)
}
}
class Corgi: Dog {
init() {
super.init(iSay: "BarkBarkBark!")
}
}
class Poodle: Dog {
init() {
super.init(iSay: "Poooooooo!")
}
}
let myCorgi = Corgi()
myCorgi.speak() // I say BarkBarkBark!
let myPoodle = Poodle()
myPoodle.speak() // I say Poooooooo!
And for the cats, this also makes sense to me, because they can either be tame or untame too, and the Cat class deals with the whole speak() function, changing the string depending on whether they're tame or not. Which I wouldn't be able to do in the Persian and Lion classes?
class Cat: Animal {
var iSay: String
var isTame: Bool
func speak() {
var tameness: String
if isTame {
tameness = "I'm tame"
} else {
tameness = "I'm not tame"
}
print("I say \(iSay) because \(tameness).")
}
init(iSay: String, isTame: Bool) {
self.iSay = iSay
self.isTame = isTame
super.init(legs: 4)
}
}
class Persian: Cat {
init() {
super.init(iSay: "Meow!", isTame: true)
}
}
class Lion: Cat {
init() {
super.init(iSay: "ROAR!", isTame: false)
}
}
let myPersian = Persian()
myPersian.speak() // I say Meow! because I'm tame.
let myLion = Lion()
myLion.speak() // I say ROAR! because I'm not tame.
Is there a reason that using override func...
for speak()
would be better? 🤔
Are there any other ways I could improve my code?