pluto pluto - 1 year ago 92
Swift Question

How to create an Single Class coexist with Generic in Swift

I have a Single Class like this:

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

But I want use Generic in this Class like this:

class Single<T: Hashable> {
static let sharedInstance: Single = Single()
var dic: [T: Any] = [:] // Here use the Generic

I got this result from Xcode

Static stored properties not supported in generic types

I have search this error in stackoverflow, but all the answer for this is not suit for me. Like this one(How to define static constant in a generic class in swift?)

How can I solve this?

Answer Source

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

class Single<T: Hashable> {
  static var sharedInstance: Single { return Single() }
  var dic: [T: Any] = [:]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download