swiftgenericssingleton

How to have a singleton instance of a generic Class in Swift?


I have a singleton Class like this:

class Single {
    static let sharedInstance: Single = Single()
    ...
}

But I want to make the class generic like this:

class Single<T: Hashable> {
    static let sharedInstance: Single = Single()
    var dic: [T: Any] = [:] // Use the generic "T" here
}

I got this error from Xcode

Static stored properties not supported in generic types

I have searched Stackoverflow but none of the answers suit me.

For example, this one How to define static constant in a generic class in swift?

How can I solve this?


Solution

  • You can declare a generic type using a static computed property as follows:

    class Single<T: Hashable> {
      static var sharedInstance: Single? {
        if self.sharedInstance != nil {
            return self.sharedInstance
        } else {
            return Single()
        }
      }
      var dic: [T: Any] = [:]
    }