Swinject is an injection environment for Swift. In your case, you can use it without translation from as? .
Registration:
let container = Container() container.register(CacheServiceProtocol.self) { _ in ImageCacheService() }
Download:
let cache = container.resolve(CacheServiceProtocol.self)!
Here cache is output as CacheServiceProtocol . The resolve method returns nil if the specified type is not registered. We know that the CacheServiceProtocol already registered, so a forced U-turn is used with ! .
UPDATE
I definitely did not answer the question. The implementation to remove the throw stores the factory closure instead of the values ββin the registry . Here is an example. I also changed the key type.
class ServiceRegistry { static var instance = ServiceRegistry() private var registry = [String:Any]() private init(){} func register<T>(key:T.Type, factory: () -> T) { self.registry["\(T.self)"] = factory } func get<T>(_:T.Type) -> T? { let factory = registry["\(T.self)"] as? () -> T return factory.map { $0() } } }
Registration:
ServiceRegistry.instance.register(CacheServiceProtocol.self) { return ImageCacheService() }
Download:
// The type of cache is CacheServiceProtocol? without a cast. let cache = ServiceRegistry.instance.get(CacheServiceProtocol.self)
Using @autoclosure can also be good.
source share