DEV Community

Lou Franco
Lou Franco

Posted on • Edited on

The Swift Programming Language Companion: Properties Part 1

This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple. This is the fourth 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.

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 "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. For Part 1, we're going to stick to the more common parts, stored properties, computed properties, and Type properties.

For these exercises, we are going to imagine a simple media playing app.

In your Playground write code to do the following:

  1. (from enumerations): Declare an enumeration called Genre and add cases for jazz, rock, rap, country, and folk.
  2. Declare an Artist struct with stored properties name and birthDate
  3. Declare a Song struct with stored properties title, artist, and genre
  4. Add a computed property to Artist called age which uses birthDate and today’s date.
  5. Declare a few Artist and Song instances
  6. Make a class called Library and add a Type property called songs that is an array of Song structs. Initialize it with a few values.

Hints

To find today’s date: let today = Date()
To find the number of seconds between two dates:
let seconds = today.timeIntervalSince(birthDate)

Next

The next article will look at the more advanced usage of properties.

Top comments (0)