I know that the book tells us to make Town a struct, but this appears to be causing problems. I use the code in the book to define Town, Monster, and Zombie (i.e., the code before the challenges). I then use the following in main.swift:
var myTown = Town()
myTown.changePopulation(by: 500)
let genericMonster = Monster()
genericMonster.town = myTown
genericMonster.terrorizeTown()
print("After generic terrorizes")
genericMonster.town?.printDescription() // population of generic monster's town
myTown.printDescription() // population of myTown
let fredTheZombie = Zombie()
fredTheZombie.town = myTown
fredTheZombie.name = "Fred the Zombie"
fredTheZombie.terrorizeTown()
print("After Fred terrorizes")
fredTheZombie.town?.printDescription() // population of Fred's town
myTown.printDescription() // population of myTown
This gives the output:
population changing by 500
Monster is terrorizing a town!
After generic terrorizes
Population: 5922, number of stoplights: 4
Population: 5922, number of stoplights: 4
population changing by -10
Fred the Zombie is terrorizing a town!
After Fred terrorizes
Population: 5912, number of stoplights: 4
Population: 5922, number of stoplights: 4
Program ended with exit code: 0
Things are OK for the generic monster, but they are wrong after Fred the Zombie terrorize. Notice that Fred’s town has a population of 5912, whereas myTown has a population of 5922. From this, it appears that Fred has been given a copy of myTown, not (a pointer to) myTown.
I can fix this behavior by defining myTown to be a class, not a struct as suggested by someone in the Bronze & Silver Challenge. This issue seems to be affecting a number of people in the Bronze & Silver Challenge thread, but it appears to me to be a problem with the code in the actual chapter.
Is my interpretation correct or is something else going on?