The Swift Programming Language Companion: Inheritance

by Lou Franco

This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple. This is the seventh article in Section 2 (here is Section 1)

Read each article after you have read the corresponding chapter in the book. This article is a companion to Inheritance.

Set up a reading environment

If you are jumping around these articles, make sure you read the Introduction to see my recommendation for setting up a reading environment.

To add a new page, in Xcode:

  1. Choose File > New > Playground Page
  2. Rename the page to "13-Inheritance"

Exercises for Inheritance

At this point, you should have read Inheritance in The Swift Programming Language. You should have a Playground page for this chapter with code in it that you generated while reading the book.

Exercises

The chapter covers how to use Inheritance.

For these exercises, we are going to imagine a simple media playing app. Use the code we developed for the chapter on Methods:

struct Song {
    let title: String
}

class Player {
    var currentSong: Song? {
        didSet {
            if let currentSong = currentSong {
                print("\(currentSong.title) is playing")
            } else {
                print("No song is playing")
            }
        }
    }
}

In the Methods chapter we added methods called play and isPlaying. Use the code that you developed from those exercises.

In your Playground write code to do the following:

  1. Make a new class called NoStairwayPlayer that inherits from Player
  2. Override the play method
  3. In the new play, check to see if the song title is "Stairway to Heaven", and if it is, don't play it (do nothing)
  4. If it isn't, call the super-class version of play.
  5. Write code to test it by checking currentSong and isPlaying

Next

The next article will provide exercises for the Initialization chapter.

Never miss an article

Get more articles like this in your inbox.