Skip to content

Instantly share code, notes, and snippets.

@Revolucent
Created January 8, 2016 07:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Revolucent/e2d73e9b08dcbe66f281 to your computer and use it in GitHub Desktop.
Save Revolucent/e2d73e9b08dcbe66f281 to your computer and use it in GitHub Desktop.
Poor Man's Dependency Resolver for Swift
enum CreationPolicy {
case Single
case Shared
}
class Resolver {
private struct Instance {
private let policy: CreationPolicy
private let create: () -> Any
private var instance: Any?
init(policy: CreationPolicy, create: () -> Any) {
self.policy = policy
self.create = create
}
mutating func get<T>(policy: CreationPolicy?) -> T {
switch policy ?? self.policy {
case .Single:
return create() as! T
case .Shared:
if instance == nil {
instance = create()
}
return instance! as! T
}
}
}
private init() {}
private static var instances = [String: Instance]()
static func resolve<R, T>(type: R, policy: CreationPolicy? = nil) -> T {
var instance = instances[String(R)]!
return instance.get(policy)
}
static func register<R, T>(type: R, policy: CreationPolicy, implementation: () -> T) {
instances[String(R)] = Instance(policy: policy, create: implementation)
}
}
protocol ServiceType {}
class Service: ServiceType {}
Resolver.register(ServiceType.self, policy: .Shared, implementation: Service.init)
let service: ServiceType = Resolver.resolve(ServiceType)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment