我有一个汽车课。假设一辆汽车去了垃圾场,这辆车不再应计入总人口。我具有DEINIT功能,但是如何系统地从汽车人口中删除汽车?换句话说,我该如何使Deinit生效?
我有一个类变量isJunk
,但不知道如何使用它来制作此工作。
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
}
}
class Car {
static var population: Int = 0
init() {
Car.population += 1
}
deinit {
Car.population -= 1
}
}
var cars: [Car] = [Car(), Car()]
print("Population:", Car.population) // "Population: 2"
// now the second car is removed from array and we have no other references to it
// it gets removed from memory and deinit is called
cars.removeLast()
print("Population:", Car.population) // "Population: 1"
但是,只需询问cars
数组中的项目数量,就可以实现同样的方法。这通常比实例的私人计数器更好。
要将项目保存在内存中,您将始终需要某种寄存器(例如数组)。该登记册可以使它们计算。
一种可能性:
class CarPopulation {
var liveCars: [Car] = []
var junkCars: [Car] = []
}
或者您可以将它们保存在一个数组中,并在汽车上设置junk
,并在需要时计算非Junk汽车:
class CarPopulation {
var cars: [Car] = []
func liveCars() -> Int {
return self.cars.filter { !$0.junk }.count
}
}
有很多可能性,但是将计数器提取到其他拥有汽车的其他类可能是一个更好的解决方案。
当您对Car
的实例进行处理时(完全摆脱对象的实例时)时,deinit
被调用。当您将Car
实例放在垃圾场中时,我认为您不想摆脱Car
的实例,您真的只想更改其位置。我建议使用其他功能来处理更改Car
的位置。
也许:
func changeLocation(newLocation: String) {
// Perhaps add an instance variable to 'remember' the location of the car
switch newLocation {
case "junkyard":
Car.population -= 1
default:
// Perhaps check whether previous location was Junkyard and increment
// counter if the Car is coming out of the Junkyard
print("Unrecognized location")
}
}