100 days of swiftui: checkpoint 7
https://www.hackingwithswift.com/quick-start/beginners/checkpoint-7
Your challenge is this: make a class hierarchy for animals, starting with Animal at the top, then Dog and Cat as subclasses, then Corgi and Poodle as subclasses of Dog, and Persian and Lion as subclasses of Cat.
But there’s more:
1. The Animal class should have a legs integer property that tracks how many legs the animal has.
2. The Dog class should have a speak() method that prints a generic dog barking string, but each of the subclasses should print something slightly different.
3. The Cat class should have a matching speak() method, again with each subclass printing something different.
4. The Cat class should have an isTame Boolean property, provided using an initializer.
class Animal {
var legs: Int
init(legs: Int) {
self.legs = legs
}
}
class Dog: Animal {
override init(legs: Int) {
super.init(legs: legs)
}
func speak() {
print("Bow!")
}
}
class Corgi: Dog {
override
func speak() {
print("Bow and i'm corgi!")
}
}
class Poodle: Dog {
override
func speak() {
print("Bow and i'm poodle!")
}
}
class Cat: Animal {
var isTame: Bool
init(legs: Int, isTame: Bool) {
self.isTame = isTame
super.init(legs: legs)
}
func speak() {
print("Meow!")
}
}
class Persian: Cat {
override
func speak() {
print("Meow and i'm persian!")
}
}
class Lion: Cat {
override
func speak() {
print("Meow and i'm lion!")
}
}
var corgi = Corgi(legs: 4)
var lion = Lion(legs: 4, isTame: false)
corgi.speak()
lion.speak()
결과:
Bow and i'm corgi!
Meow and i'm lion!
코드 파일
https://github.com/soaringwave/Ios-studying/commit/e1d240d89c7c513326332f0ce33fed1b560a2124