如何使deinit快速生效 [英] how to make deinit take effect in swift

查看:104
本文介绍了如何使deinit快速生效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有汽车课.假设有一辆汽车驶进垃圾场,那么这辆汽车就不应再计入总人口中.我具有deinit函数,但是如何系统地从汽车中删除汽车?换句话说,如何使deinit生效?

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?

我有一个类变量isJunk,但不知道如何使用它来完成这项工作.

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
    }
}

推荐答案

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数组中的项数就可以实现相同的目的.通常,这是比实例私有计数器更好的选择.

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.

一种可能性:

class CarPopulation {
    var liveCars: [Car] = []
    var junkCars: [Car] = []
}

或者您可以将它们放在一个阵列中,并在车上设置junk,并在需要时计算非垃圾车:

Or you can keep them in one array and set junk on the car and count non-junk cars when needed:

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

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

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

There are many possibilities but extracting the counters to some other class that owns the cars is probably a better solution.

这篇关于如何使deinit快速生效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆