如何计算Swift中一个类的实例数量?我有以下课程:
class car {
static var car人口:Int = 0
var color :字符串
var容量:Int
var驱动程序:布尔?
var carOn:布尔=假
init(carColor:String,carCapacity:Int){
self.capacity = carCapacity
self.color = carColor
car人口++ // #########给我错误##############
}
func startCar(){
self.carOn = true
}
}
类赛车:car {
var nitro:Bool
init(carColor:String,carCapacity:Int,hasNitro:Bool) {
self.nitro = hasNitro
super.init(carColor:carColor,carCapacity:carCapacity)
}
}
car.CarPopulation //输出在xcode操场上$ 0
我假设我需要一个函数来实际返回值,但是我想要
我收到以下错误:
错误:静态成员'carPopulation'不能用于类型'car'的实例
内部初始化方法中,您必须使用
Car.carPopulation + = 1 $ b向静态var中添加一个$ b
您必须实施反初始化程序以删除将要消失的汽车实体
deinit
{
Car.carPopulation-= 1
}
How do you count the number of instances of a class in Swift? I have the following class:
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
I am assuming I need a function to actually return the value, but I want the counter to increase every time an instance of the class is created.
I get the following error:
error: static member 'carPopulation' cannot be used on instance of type 'car'
Inside initializer method you have to add one to your static var with
Car.carPopulation += 1
And you must implement de deinitializer to delete the car entity that is going to disappear
deinit
{
Car.carPopulation -= 1
}
这篇关于计算一个类迅速实例的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!