Reputation: 3099
class mySuperClass{
static var sharedInstance = mySuperClass()
var test = "hello"
}
In this little snippet, I am setting a static var to mySuperClass() to create a simple singleton.
Is there a way to do this without using the class name mySuperClass?
I ask, because I want to subclass something like this and have the subclass create a sharedInstance of itself and NOT of the super class which is what it does.
Full code here (playground-able):
import Cocoa
class mySuperClass{
static var sharedInstance = mySuperClass()
var test = "hello"
}
class mySubClass:mySuperClass{
override init() {
super.init()
test = "hello from subclass"
}
}
print(mySuperClass.sharedInstance.test)
print(mySubClass.sharedInstance.test) //prints test from mySuperClass not subClass
Upvotes: 2
Views: 86
Reputation: 59526
In other words you want to subclass a Singleton.
Let me know if this does solve your problem.
class MySuperClass {
private static let superClassInstance = MySuperClass()
class var sharedInstance: MySuperClass { return superClassInstance }
private init() { }
var test = "hello"
}
class MySubClass: MySuperClass {
private static let subClassInstance = MySubClass()
override class var sharedInstance: MySubClass { return subClassInstance }
private override init() {
super.init()
test = "hello from subclass"
}
}
print(MySuperClass.sharedInstance.test) // "hello"
print(MySubClass.sharedInstance.test) // "hello from subclass"
Upvotes: 2