Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - what 'class var' means

Tags:

swift

This is one of the solutions to implement singleton in swift. I am confused why there is a 'class' added in front of 'var'. As far as i know, the class variable is not supported by swift, why 'class var' work in this case?

class Singleton {
    class var sharedInstance : Singleton {
        struct Static {
            static let instance : Singleton = Singleton()
        }
        return Static.instance
    }
}
like image 601
lorcel Avatar asked Sep 08 '14 18:09

lorcel


2 Answers

That's not a class variable, it's a class computed property, which is currently supported.

// Playground - noun: a place where people can play

class A {
    // Fine:
    class var computed: String {
        return "Woo"
    }
    // Not supported (yet):
    class var realVariable: String = "Woo"
}
like image 106
Matt Gibson Avatar answered Oct 20 '22 21:10

Matt Gibson


A class variable is like a static variable in that you access it by calling MyClass.myVar however static variables can't be overwritten in subclasses, while class variables can be.

like image 4
Casebash Avatar answered Oct 20 '22 21:10

Casebash