Skip to content

Instantly share code, notes, and snippets.

@asobolevsky
Created June 6, 2020 11:04
Show Gist options
  • Save asobolevsky/e2e04b950bdfae800e22e15d2e6b8c27 to your computer and use it in GitHub Desktop.
Save asobolevsky/e2e04b950bdfae800e22e15d2e6b8c27 to your computer and use it in GitHub Desktop.
protocol ServiceLocating {
func getService<T>() -> T?
}
final class ServiceLocator: ServiceLocating {
private lazy var services: Dictionary<String, Any> = [:]
private func typeName(some: Any) -> String {
return (some is Any.Type) ?
"\(some)" : "\(type(of: some))"
}
func addService<T>(service: T) {
let key = typeName(some: T.self)
services[key] = service
}
func getService<T>() -> T? {
let key = typeName(some: T.self)
return services[key] as? T
}
public static let shared = ServiceLocator()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment