I’m looking to understand why the thisTown.population (Vampire.swift) count doesn’t decrease until after the 2nd terrorizeTown(). Population (Town.swift) appears to be correct whereas thisTown.population (Vampire.swift) is off by 1.
What am I missing to get these in sync?
main.swift
import Foundation
var myTown = Town()
let keseyTheVamp = Vampire()
keseyTheVamp.town = myTown
keseyTheVamp.terrorizeTown()
keseyTheVamp.town?.printDescription()
//Terrorize #1
keseyTheVamp.terrorizeTown()
keseyTheVamp.town?.printDescription()
//Terrorize #2
keseyTheVamp.terrorizeTown()
keseyTheVamp.town?.printDescription()
//Terrorize #3
keseyTheVamp.terrorizeTown()
keseyTheVamp.town?.printDescription()
Town.swift
import Foundation
struct Town {
var population = 10
var numberOfStopLights = 4
func printDescription() {
print("Population: \(population) ; # of Stop Lights:
\(numberOfStopLights)")
}
mutating func changePopulation(by amount: Int) {
population += amount
}
}
Vampire.swift
import Foundation
class Vampire: Monster {
var thralls = [Vampire]()
override func terrorizeTown() {
if let thisTown = town {
print("\(name) is terrorizing a town!")
if thisTown.population >= 1 {
thralls.append(Vampire())
town?.changePopulation(by: -1)
print("There are \(thralls.count) thralls and
\(thisTown.population) people.")
} else {
print("There are no people left in this town!")
}
} else {
print("\(name) hasn't found a town to terrorize yet...")
}
}
}
Console
//Terrorize #1
Monster is terrorizing a town!
There are 1 thralls and 10 people.
Population: 9 ; # of Stop Lights: 4
//Terrorize #2
Monster is terrorizing a town!
There are 2 thralls and 9 people.
Population: 8 ; # of Stop Lights: 4
//Terrorize #3
Monster is terrorizing a town!
There are 3 thralls and 8 people.
Population: 7 ; # of Stop Lights: 4