Reputation: 35
I'm learning swift from a book and typed an example of structs and classes. However the example does not work like it should because the program won't decrease the population whenever a zombie is called. I know this is a stupid question but I just can't understand why. Can somebody explain what's wrong? So here's the code:
main.swift
import Foundation
var myTown = Town()
myTown.changePopulation(by:500)
let fredTheZombie = Zombie()
fredTheZombie.town = myTown
fredTheZombie.terrorizeTown()
fredTheZombie.town?.printDescription()
myTown.printDescription()
Town.swift
import Foundation
struct Town {
var population = 5422
var numberOfStopLights = 4
func printDescription() {
print("Population: \(myTown.population), number of stoplights: \ . (myTown.numberOfStopLights).")
}
mutating func changePopulation(by amount: Int){
population += amount
}
}
Monster.swift
import Foundation
class Monster{
var town: Town?
var name = "Monster"
func terrorizeTown(){
if town != nil{
print("\(name) is terrorazing a town!")
}
else{
print("\(name) hasn't found a town to terrorize yet...")
}
}
}
Zombie.swift
import Foundation
class Zombie: Monster {
override func terrorizeTown() {
town?.changePopulation(by: -10)
super.terrorizeTown()
}
}
Upvotes: 1
Views: 476
Reputation: 1340
If you change Town from a struct to a class it will work.
A struct is copied each time you assign it, so when you put zombie.town = myTown it is not the same town, the zombie has a copy of the town and the original town is not changed when the zombie's town is updated. A class will work the way you expect it to.
Upvotes: 1
Reputation: 10199
Since Town
is a struct, it will be copied when you assign it to your zombie. Therefore, fredTheZombie.terrorizeTown()
terrorizes a copy of myTown
- so myTown
keeps it's value.
What you want is a class, which will be transferred by reference when you assign it to your monster -- so you only have one Town:
class Town {
var population = 5422
var numberOfStopLights = 4
func printDescription() {
print("Population: \(myTown.population), number of stoplights: \ . (myTown.numberOfStopLights).")
}
func changePopulation(by amount: Int){
population += amount
}
}
Upvotes: 1