NEW: Learn to build the incredible iOS 15 Weather app today! >>

Checkpoint 7

Paul Hudson    @twostraws   

Updated for Xcode 13.2

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:

  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.

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:

  1. You’ll need seven independent classes here, of which only one has no parent class.
  2. To make one class inherit from another, write it like this: class SomeClass: OtherClass.
  3. You can make subclasses have a different speak() method to their parent by using the override keyword.
  4. All our subclasses have four legs, but you still need to make sure you pass that data up to the Animal class inside the Cat initializer.
Hacking with Swift is sponsored by Essential Developer

SPONSORED Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for iOS devs who want to become complete Senior iOS Developers.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.