4

I need to create a singleton for a generic class in Swift, but Generic Class in Swift don´t support static stored properties, then this methods aren`t valid

 public final class ApiClient<T>: ApiClientFor<T> where T:EntityType {        

        // Method 1

       class var shared: ApiClient<T> {
            struct Static {
                static let instance = ApiClient<T>()
            }
            return Static.instance
        }

        //Or more simple Method 2

       static let instance = ApiClient<T>()
}
fonologico
  • 43
  • 4
  • 1
    Possible dupe? [Creating a generic singleton](http://stackoverflow.com/q/29570027/2415822), [Combine generics and extensions in Swift?](http://stackoverflow.com/q/24043898/2415822) – JAL May 08 '17 at 14:10

1 Answers1

1

The fundamental problem here is that you're creating a whole family of singletons (one for each parameterized type) and each singleton needs to be stored (or referenced from) the static context. And the singletons need to be indexed by the type that they store.

I suggest creating a single, global dictionary in which to store your singletons, indexed by string descriptions of their types:

var singletons_store : [String, AnyObject]

Then in your computed shared variable you look in that store for the singleton that corresponds to a parameterized type:

class var shared : APIClient<T> {
    let store_key = String(describing: T.self)
    if let singleton = singletons_store[store_key] {
        return singleton as! APIClient<T>
    } else {
        let new_singleton = APIClient<T>()
        singleton_store[store_key] = new_singleton
        return new_singleton
    }
}
Scott Thompson
  • 22,629
  • 4
  • 32
  • 34