I have a Car class. Let's say a car goes to the junkyard, this car should no longer be counted in the total population. I have the deinit function, but how do I systematically remove a car from the car population? In other words, how do I get the deinit to take effect?
I have a class variable isJunk
but don't know how to use it to make this work.
class Car {
static var population: Int = 0
var isJunk: Bool = false
var color: String
var capacity: Int
var driver: Bool?
var carOn: Bool = false
init (carColor: String, carCapacity: Int) {
self.capacity = carCapacity
self.color = carColor
Car.population += 1
}
deinit {
Car.population -= 1
}
func startCar() {
self.carOn = true
}
}
However, the same can be achieved just by asking the number of items in
cars
array. And that's usually a better alternative than a private counter of instances.To keep the items in memory you will always need some kind of register (e.g. an array) for them. And that register can keep them counted.
One possibility:
Or you can keep them in one array and set
junk
on the car and count non-junk cars when needed:There are many possibilities but extracting the counters to some other class that owns the cars is probably a better solution.
The
deinit
is called when you deallocate your instance ofCar
(when you entirely get rid of the instance of the object). When you put aCar
instance in the junkyard I don't think you want to get rid of the instance ofCar
, you really just want to change its location. I would suggest a different function to handle changing the location ofCar
.Perhaps: