Is it possible to add subclassed objects to a static array inside the parent class? I would like to run a function on all instances created. Another SO question describes being able to loop over an array to call a function on each instance and I think this is the end result I would like as well but my problem is even getting the instances into a static array that keeps track of all instances.
Of course my code is more modular but here is a simplified view of the code and hierarchy:
class Jungle {
static var jungle: [Animals] = []
}
class Tigers: Animals {
static var tigerPopulation: Int = 0
override init(name:String){
super.init(name: name)
Tigers.tigerPopulation += 1
}
deinit {
Tigers.tigerPopulation -= 1
}
}
class Monkeys: Animals {
static var monkeysPopulation: Int = 0
override init(name: String){
super.init(name: name)
Monkeys.monkeysPopulation += 1
}
deinit {
Monkeys.monkeysPopulation -= 1
}
}
class Snakes: Animals {
static var snakePopulation: Int = 0
override init(name: String){
super.init(name: name)
Snakes.snakePopulation += 1
}
deinit {
Snakes.snakePopulation -= 1
}
}
I get the feeling that I should have created the Jungle class first so they all would subclass from Jungle I guess but I'm still stumped on how I would get the instances into an array.
Jungle.jungle.appendwont work?