Skip to content

Instantly share code, notes, and snippets.

@volkdmitri
Created January 7, 2016 21:23
Show Gist options
  • Save volkdmitri/8757016cfca83764f380 to your computer and use it in GitHub Desktop.
Save volkdmitri/8757016cfca83764f380 to your computer and use it in GitHub Desktop.
Service Locator pattern implementation in Swift 2.
class ServiceLocator {
lazy var s = [String: Any]()
func add(services: Any...) {
for service in services {
s[typeName(service)] = service
}
}
func get<T>(_: T.Type) -> T? {
return s[typeName(T)] as? T
}
private func typeName(some: Any) -> String {
return (some is Any.Type) ? "\(some)" : "\(some.dynamicType)"
}
}
//Example
class Service1 {
func description() -> String {
return "Hello! I'm Service1"
}
}
class Service2 {
func description() -> String {
return "Hello! I'm Service2"
}
}
let sl: ServiceLocator = {
let sl = ServiceLocator()
sl.add(Service1(), Service2())
return sl
}()
sl.get(Service1)?.description() //"Hello! I'm Service1"
sl.get(Service2)?.description() //"Hello! I'm Service2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment