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 eighth 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:
- Choose File > New > Playground Page
- 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:
- Make a new class called
NoStairwayPlayer
that inherits fromPlayer
- Override the
play
method - 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) - If it isn't, call the super-class version of
play
. - Write code to test it by checking
currentSong
andisPlaying
Next
The next article will provide exercises for the Initialization chapter.
Next Article: The Swift Programming Language Companion: Initialization