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
}
}
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"
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With