iOS: Subclass singleton in swift

Viewed 872

I have a framework where I have a singleton class, let's say Singleton. This class is used by other classes in the framework.

In the app project I want to subclass this singleton class, e.g. AppSingleton: Singleton. Is it possible? What is the right solution?

1 Answers

I provide a solution but it may be a little hacky.

Class A {
  open class var shared: A {
    return A.privateShared
  }
  private static let privateShared = A()
}

Class B {
  open class var shared: B {
    return A.privateShared
  }
  private static let privateShared = B()
}

I must clarify, this ways isn't perfect since it actually create 2 instance! So, it will technically not a singleton any more.

However, you can override the class B's property or method to call A.shared method or property instead. You must know what you are doing and consider use the other way to fix the problem you want to solve.

Related