DEV Community

Lou Franco
Lou Franco

Posted on • Edited on • Originally published at app-o-mat.com

The Swift Programming Language Companion: Properties Part 2

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:

  1. Declare a Player class
  2. Add a var property to Player called currentSong that is of type Song? (we created Song in the last chapter)
  3. Add a didSet property observer to currentSong. In it, print the title of the currentSong with “ is playing” appended to it (use String interpolation)
  4. Construct a Player and set currentSong to a few different Song values.
  5. In your didSet, when the new value is nil, print “No song is playing”
  6. Set currentSong of your Player object to nil

Next

The next article will provide exercises for the Methods chapter.

Top comments (0)