Skip to content

Instantly share code, notes, and snippets.

@zvonicek
Last active November 23, 2016 14:27
Show Gist options
  • Save zvonicek/1b1af84e422a3ef4d10a4daa1a4e83f3 to your computer and use it in GitHub Desktop.
Save zvonicek/1b1af84e422a3ef4d10a4daa1a4e83f3 to your computer and use it in GitHub Desktop.
ServiceHolder
import Foundation
protocol Service {
init()
}
class ServiceHolder {
private var servicesDictionary: [String: Service] = [:]
init(services: [Service.Type]? = nil) {
services?.forEach {
self.add($0)
}
}
func add(_ type: Service.Type, with name: String? = nil) {
let name = name ?? String(reflecting: type)
servicesDictionary[name] = type.init()
}
func add<T>(_ protocolType: T.Type, for concreteType: Service.Type, with name: String? = nil) {
let name = name ?? String(reflecting: protocolType)
servicesDictionary[name] = concreteType.init()
}
func add(_ type: Service.Type, with name: String? = nil, constructor: () -> Service) {
let name = name ?? String(reflecting: type)
servicesDictionary[name] = constructor()
}
func get<T>(by type: T.Type = T.self) -> T {
return get(by: String(reflecting: type))
}
func get<T>(by name: String) -> T {
guard let service = servicesDictionary[name] as? T else {
fatalError("firstly you have to add the service")
}
return service
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment