Created
January 7, 2016 21:23
-
-
Save volkdmitri/8757016cfca83764f380 to your computer and use it in GitHub Desktop.
Service Locator pattern implementation in Swift 2.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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