Programming in Swift · Memory Management |

This is a companion discussion topic for the original entry at

How “var bestBuddy: Person?” is possible if bestBuddy inside Person class?

It works because classes are reference types. That is, instead of storing the Person’s data, you store a place in memory to get a Person.

If you try it with a struct, it won’t compile!

struct Person {
  let person: Person // Error: Value type 'Person' cannot have a stored property that recursively contains it

The capability of a class to reference an instance of itself is not totally unlike recursive functions:

func countDown(from number: Int) {
  guard number > 0 else {
    print("Blast Off! 🚀")

  countDown(from: number - 1)

countDown(from: 10)

// 10
// 9
// 8
// 7
// 6
// 5
// 4
// 3
// 2
// 1
// Blast Off! 🚀


Can you explain why you needed the ? when doing the following code:

loki?.bestBuddy = catty

I watched the Optionals video and we only used ? when defining the constant/variable. We never used ? when later referring to those constants/variables.

Did I miss a video?

Thanks :slight_smile:

This syntax is known as optional chaining. It’s a more concise way of writing this:

if let loki = loki {
  loki.bestBuddy = catty

Sorry that we missed naming the concept in this course. We’ll rectify that in the update, coming soon!

1 Like