Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.


Class variables

The languages I used most before the change to Swift were Objective-C and Java. When Apple announced swift, a modern OO language, one of my first "disappointments" with Swift were the missing Class variables.

In Java Class variables are simply defined by using the 'static' keyword. I.e.:

class MyClass {
    static int myClassVariable;


In Objective-C there was no direct class variable, we had to define them outside the class, and when visibility was an issue, they had to be hidden in an implementation file. A bit of a kludge if you ask me.

In Swift, the approach is very much like Objective-C, but the visibility problem is easily solved by using the 'private' keyword. Example:

private var myClassVariable: Int

class MyClass {


This approach has started to grow on me. I now like this better than the Java class variables. I find it more intuitive. After all, a class variable belongs to a class, but is not part of an object. Defining it outside the class makes this distinction clear in the code itself. The proximity with the class is still present because it has to be in the same file as the class definition.

While in the beginning I hoped that Apple would support class variables, I now think that this issue has become moot.

Edit 2015.04.05: In Swift 1.2 (comes with xcode 6.3) the "static" keyword can be used to define class variables just like in Java.

class MyClass {
    static var instanceCount: Int = 0
    init() {
        MyClass.instanceCount += 1


Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment