Learn
Structures
Structures are Value Types

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 of Dog, that was initialized with the properties: age: 5 and isGood: true.
  • Immediately afterward, we create another variable oldDog that has the value of youngDog.
  • We assign the age of oldDog a value of 10, but we left youngDog alone.
  • When we print oldDog.age it prints 10.
  • When we print youngDog.age it prints 5. ๐Ÿค”

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

1.

In Darwin.swift, under the created groundFinch, create another variable called cactusFinch that has the value of groundFinch.

2.

Assign the cactusFinch.nestLocation to "Cactus".

3.

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.

Folder Icon

Take this course for free

Already have an account?