Skip to content

Instantly share code, notes, and snippets.

@cmittendorf
Last active July 13, 2016 12:45
Show Gist options
  • Save cmittendorf/b155d12004d3aef71481a430495392fb to your computer and use it in GitHub Desktop.
Save cmittendorf/b155d12004d3aef71481a430495392fb to your computer and use it in GitHub Desktop.
A simple ServiceLocator written in Swift.
protocol ServiceLocatorType {
func getService<T>(type: T.Type) -> T
}
public final class ServiceLocator: ServiceLocatorType {
public static let instance = ServiceLocator()
private var serviceRegistry: [String:Any] = [:]
private init() {}
func addService<T>(instance: T) {
let key = String(T)
serviceRegistry[key] = instance
}
func getService<T>(type: T.Type) -> T {
let key = String(T)
if let service = serviceRegistry[key] as? T {
return service
} else {
fatalError("A service of \(String(T)) is not registered!")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment