mardi 15 août 2017

Swift singleton subclass(inheritance)

I know the simplest way to write singleton in swift is

class A {
    static let shared = A()
    private init() { //... }
    func a() {}
}
// usage
A.shared.a()

the question is that is it possible to write a subclass singleton of class A?

I got the following code from someone to do it by class function

class A {
    class func shared() -> A {
        private struct _A {
            static let _shared = A()
        }
        return _A.shared
    }
    func a() { //... }
}
class B: A {
    class func shared() -> B {
        private struct _B {
            static let _shared = B()
        }
        return _B.shared
    }
    func b() { //... }
}
// usage
A.shared.a()
B.shared.b()

but the problem is that I can't use private init() to hide initialization here, since there is no protected init() to do this

Does anyone know how to subclass a singleton class by using the private init()? thanks!

Aucun commentaire:

Enregistrer un commentaire