Updated for Xcode 15
Now that you understand how classes work, and, just as importantly, how they are different from structs, it’s time to tackle a small challenge to check your progress.
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:
Animal
class should have a legs
integer property that tracks how many legs the animal has.Dog
class should have a speak()
method that prints a generic dog barking string, but each of the subclasses should print something slightly different.Cat
class should have a matching speak()
method, again with each subclass printing something different.Cat
class should have an isTame
Boolean property, provided using an initializer.I’ll provide some hints in a moment, but first I recommend you go ahead and try it yourself.
Hacking with Swift+ subscribers can get a complete video solution for this checkpoint here: Solution to Checkpoint 7. If you don’t already subscribe, you can start a free trial today.
Still here? Okay, here are some hints:
class SomeClass: OtherClass
.speak()
method to their parent by using the override
keyword.Animal
class inside the Cat
initializer.BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.