在Swift中,是否存在类似self的关键字,但是对于类?

时间:2016-01-03 22:58:54

标签: swift static singleton subclass

class mySuperClass{
    static var sharedInstance = mySuperClass()
    var test = "hello"
}

在这个小片段中,我将一个静态var设置为mySuperClass()来创建一个简单的单例。

有没有办法在不使用类名mySuperClass的情况下执行此操作?

我问,因为我想要继承这样的东西并让子类创建一个自己的sharedInstance而不是它所做的超级类。

这里的完整代码(可操场):

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

1 个答案:

答案 0 :(得分:2)

换句话说,你想要继承Singleton

如果这确实解决了您的问题,请告诉我。

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"