In Swift, data types can be value types or reference types. This means that different data types are stored and accessed in different ways. Structures are value types, this means every time an instance is created or copied, the instance has its own set of unique values. Weโll cover reference types in a separate lesson.
For example:
var youngDog = Dog(age: 5, isGood: true) var oldDog = youngDog oldDog.age = 10 print(oldDog.age) // Prints: 10 print(youngDog.age) // Prints: 5
There are some nuances that we should go over from the example above.
- First we created
youngDog
, an instance ofDog
, that was initialized with the properties:age: 5
andisGood: true
. - Immediately afterward, we create another variable
oldDog
that has the value ofyoungDog
. - We assign the
age
ofoldDog
a value of10
, but we leftyoungDog
alone. - When we print
oldDog.age
it prints10
. - When we print
youngDog.age
it prints5
. ๐ค
We may have thought that since we changed oldDog.age
that it would also affect youngDog
since oldDog
was copied from youngDog
. But remember and go back to our main point structs are value types. When we created oldDog
using youngDog
, oldDog
is only storing the values of youngDog
. The takeaway here is that: any changes we make to an instance of a structure, like oldDog
, itโs properties will not affect other instances.
Instructions
In Darwin.swift, under the created groundFinch
, create another variable called cactusFinch
that has the value of groundFinch
.
Assign the cactusFinch.nestLocation
to "Cactus"
.
Time to check the values and confirm that only cactusFinch
โs .nestLocation
changed.
Add a print()
statement and print out cactusFinch.nestLocation
.
In a separate print()
, output the value of groundFinch.nestLocation
.