Last active
August 29, 2015 14:07
-
-
Save chakrit/019bc39591751beaf4cf to your computer and use it in GitHub Desktop.
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
class Container { | |
typealias Resolver = () -> AnyObject | |
private var _resolvers: [String: Resolver] = [:] | |
func register<T: AnyObject>(resolver: @autoclosure () -> T) { | |
let name = NSStringFromClass(T.self) | |
_resolvers[name] = resolver | |
} | |
func get<T: AnyObject>() -> T { | |
let name = NSStringFromClass(T.self) | |
if let resolver = _resolvers[name] { | |
return resolver() as T | |
} else { | |
fatalError("no registration for requested type") | |
} | |
} | |
} | |
prefix operator <- {} | |
infix operator <- {} | |
prefix func <-<T: AnyObject>(container: Container) -> T { | |
return container.get() | |
} | |
func <-<T: AnyObject>(container: Container, registration: @autoclosure () -> T) { | |
container.register(registration) | |
} |
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
class A: NSObject { } | |
class B: NSObject { } | |
let a = A() | |
let b = B() | |
let container = Container() | |
container <- a // singleton | |
container <- B() // factory | |
class Dependent { | |
let a: A = <-container | |
let b: B = <-container | |
} | |
let dep = Dependent() | |
if dep.a == a { print("a ok") } | |
if dep.b != b { print("b ok") } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment