checkpoint 7: Animal class

그루두·2024년 4월 21일
0

100 days of SwiftUI

목록 보기
19/108

100 days of swiftui: checkpoint 7
https://www.hackingwithswift.com/quick-start/beginners/checkpoint-7

challenge

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.

Solution

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

profile
계속 해보자

0개의 댓글

관련 채용 정보