This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple. This is the fifth 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 Properties.
This is Part 2 of the Properties companion. It builds on Properties Part 1, so read that if you have not and do the exercises. The exercises in this chapter require that you have done those already.
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.
We can continuing using the page we made for Part 1 ("10-Properties").
Exercises for Properties
At this point, you should have read Properties 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 declare Properties inside of Structures and Classes. In Part 1, we had exercised for stored properties, computed properties, and Type properties.
In Part 2, we’re going to look at Property Observers.
For these exercises, we are going to continue with the code we built in the last chapter.
In your Playground write code to do the following in the same playground that you used for Properties Part 1:
- Declare a
Player
class - Add a
var
property toPlayer
calledcurrentSong
that is of typeSong?
(we createdSong
in the last chapter) - Add a
didSet
property observer tocurrentSong
. In it, print the title of thecurrentSong
with “ is playing” appended to it (use String interpolation) - Construct a
Player
and setcurrentSong
to a few differentSong
values. - In your
didSet
, when the new value isnil
, print “No song is playing” - Set
currentSong
of yourPlayer
object to nil
Next
The next article will provide exercises for the Methods chapter.
Top comments (0)