Reputation: 40
I have a struct Town
with a population of 11
struct Town {
var population: Int = 11 {
didSet(oldPopulation){
print("The population has changed to \(population) from \(oldPopulation)")
}
}
}
and I have a mutating function
mutating func changePopulation(amount: Int) {
population += amount
}
I created a zombie class that calls a function that decreases population by 10
final override func terrorizeTown() {
guard var town = town else {
return
}
town.population <= 0 ? print("no people to terrorize") : town.changePopulation(amount: -10)
super.terrorizeTown()
}
when I run this i the main.swift file
var myTown = Town()
var fredTheZombie = Zombie()
fredTheZombie.name = "Fred"
fredTheZombie.town = myTown
//myTown.changePopulation(amount: 0)
print(myTown.population)
fredTheZombie.terrorizeTown()
print(myTown.population)
What I don't understand is the results..
11
The population has changed to 1 from 11
Fred is terrorizing a town!
11
Why is it that when I print (myTown.population) again do i receive a value of 11, when I have called a mutating function on the property. I don't understand.. should the result not be 1, why do i get 11?
Upvotes: 0
Views: 461
Reputation: 534950
It is because the line guard var town = town
makes a copy of your Town object. Hence, it is the copy that is mutated.
Upvotes: 1