3

我有一个汽车课。假设一辆汽车去垃圾场,这辆车不应该再计入总人口中。我有 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
    }
}
4

2 回答 2

5
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在汽车上并在需要时计算非垃圾车:

class CarPopulation {
    var cars: [Car] = []

    func liveCars() -> Int {
        return self.cars.filter { !$0.junk }.count
    }
}

有很多可能性,但将计数器提取到拥有汽车的其他类别可能是更好的解决方案。

于 2016-06-24T21:28:38.107 回答
1

deinit您释放实例时Car(当您完全摆脱对象的实例时)调用 。当您将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")
   }

}
于 2016-06-24T21:33:42.840 回答