Last active
July 13, 2016 12:45
-
-
Save cmittendorf/b155d12004d3aef71481a430495392fb to your computer and use it in GitHub Desktop.
A simple ServiceLocator written in Swift.
This file contains 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
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