mercredi 10 juin 2015

Is there a better way to do dependency injection in Swift than this ?

New to swift, I was trying to create a service registry:

class ServiceRegistry {

    static var instance = ServiceRegistry()

    private var registry = [String:AnyObject]()
    private init(){}

    func register<T>(key:T, value:AnyObject) {
        self.registry["\(T.self)"] = value
    }

    func get<T>(_:T) -> AnyObject? {
        return registry["\(T.self)"]
    }

}

but is not super friendly:

Register:

 ServiceRegistry.instance.register(CacheServiceProtocol.self, value:ImageCacheService())

Retrieve:

if let cache = ServiceRegistry.instance.get(CacheServiceProtocol) as? CacheServiceProtocol { ... }

Any better way ? It would be useful to get rid of the as? CacheServiceProtocol in the if let ...

Aucun commentaire:

Enregistrer un commentaire