Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count number of instances of a class swift

Tags:

class

swift

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'

like image 669
Govind Rai Avatar asked Jun 24 '16 20:06

Govind Rai


People also ask

What is instance of class in Swift?

Swift ObjectsAn object is called an instance of a class. For example, suppose Bike is a class then we can create objects like bike1 , bike2 , etc from the class. Here's the syntax to create an object. var objectName = ClassName()


2 Answers

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
}
like image 54
Adolfo Avatar answered Oct 19 '22 13:10

Adolfo


you need to call car.carpopulation += 1 as the carpopulation is bound to the class car.

here is the working code

var str = "Hello, playground"

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
        car.carPopulation += 1 //no longer an 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

// now initialize a car
var raceC = raceCar(carColor: "black", carCapacity: 4, hasNitro: false)

// check again
car.carPopulation 
like image 2
Jason K Avatar answered Oct 19 '22 11:10

Jason K