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.
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").
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.
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
- Add a
currentSongthat is of type
Songin the last chapter)
- Add a
didSetproperty observer to
currentSong. In it, print the title of the
currentSongwith “ is playing” appended to it (use String interpolation)
- Construct a
currentSongto a few different
- In your
didSet, when the new value is
nil, print “No song is playing”
Playerobject to nil
The next article will provide exercises for the Methods chapter.