This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple. This is the third 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 Structures and Classes.
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:
At this point, you should have read Structures and Classes 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.
This chapter is not so much about how to make Structures and Classes, but more about the difference between them. They both have properties and methods (as we'll see in the next two chapters), and are sometimes interchangeable. To beginners, it can be confusing to tell the difference between them or decide when to use one over the other.
Structure instances are values. We have already seen many other values, like
String, and enumerations. Values can never change.
5 is a value, and it makes no sense to change
6 -- I can add the value
1 to the value
5 and get a new value
6, but I can't change
5. I can't change
"Hello" and I can't change
June 8, 2020.
If I have a variable that is set to a value, I can change which value it is set to, but I cannot change the value itself. For example:
var a = 5 var b = a a += 1 // b is still 5 -- a refers to a new value
Class instances are objects with identity. It is possible to change them, and individual objects can be told apart (whereas every equal value is completely indistinguishable). If multiple variables refer to the same object, and we change it, we can see that change using any variable that refers to that same object.
Even if two objects are equivalent, they might not be identical. If I copy an object to a new one, the copy will not change if I change the original one.
You will learn when to use one or the other through experience. To start with, try to favor structs over classes.
The chapter covers how to declare Structures and Classes and the differences between them.
For these exercises, we are going to imagine a simple media playing app.
In your Playground write code to do the following:
SongStruct). Songs have a
artist, and a
SongClass). Add the same three properties
var b = a) first and see if changing
The next article will provide exercises for the Properties chapter.