Instances are not related


#1

In main.swift, when I create an instance of any of the objects, then assign 1 object as a property of another, it treats both instances separately.

For example…
var bronzeTown = Town()
var bronzeVampire = Vampire()
bronzeVampire.town = bronzeTown
bronzeTown.printDescription() // PRINTS "Pop 5422…"
bronzeVampire.town?.printDescription() // PRINTS “Pop 5422…” - no terrorising has happened
bronzeVampire.terroriseTown()
bronzeTown.printDescription() // PRINTS “Pop 5422…” - still at default! Why???
bronzeVampire.town?.printDescription() // PRINTS “Pop 5421…” - shows the expected lower number…

I can paste in the full code, but if someone is able to pinpoint the Swift term for this, as I am sure I remember something about this in the chapter, just cant recall what it was…


#2

You are probably creating object instances from struct elements. Remember that instances of struct elements are value types, not reference types. This means that if you assign an instance of a struct to another instance, you will end up with two independent instances, which are exact replicas.


#3

Thanks ibex, that was the answer.

My “town” was a struct. I replicated it as a class, recreating sub-classes and other references to other objects correctly. Changing population (either directly using my .changePop(number:) function or through the terrorisetown() function) and then printing both the direct class instance AND that class instance assigned to my Monster returned the same results.