count swift类的实例数

时间:2016-06-24 20:45:09

标签: swift class

如何计算Swift中类的实例数?我有以下课程:

class car {
    static var carPopulation: Int = 0
    var color: String
    var capacity: Int
    var driver: Bool?
    var carOn: Bool = false
    init (carColor: String, carCapacity: Int) {
        self.capacity = carCapacity
        self.color = carColor
        carPopulation ++ //##########GIVES ME ERROR#############
    }
    func startCar() {
        self.carOn = true
    }
}

class raceCar : car {
    var nitro: Bool
    init(carColor: String, carCapacity: Int, hasNitro: Bool) {
        self.nitro = hasNitro
        super.init(carColor: carColor, carCapacity: carCapacity)
    }
}

car.CarPopulation //outputs 0 in xcode playground

我假设我需要一个函数来实际返回值,但我希望每次创建类的实例时计数器都会增加。

我收到以下错误:

error: static member 'carPopulation' cannot be used on instance of type 'car'

2 个答案:

答案 0 :(得分:9)

在初始化程序内部方法中,您必须使用

将静态变量添加到静态变量中
Car.carPopulation += 1

您必须实施de deinitializer以删除即将消失的汽车实体

deinit
{
    Car.carPopulation -= 1
}

答案 1 :(得分:1)

你需要打电话给car.carpopulation + = 1,因为车厢必然会被这辆车所包围。

这是工作代码

select m.*, mp.*, p.* from (select id from matchh limit 5,10) m
        left outer join match_player mp on m.id=mp.matchid 
        left outer join Player p on mp.playerid=p.id;