Created
May 1, 2020 17:44
-
-
Save hannessolo/984a2e6244226906dbaf49102b35b041 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
struct DependencyInjector { | |
private static var dependencyList: [String:Any] = [:] | |
static func resolve<T>() -> T { | |
guard let t = dependencyList[String(describing: T.self)] as? T else { | |
fatalError("No povider registered for type \(T.self)") | |
} | |
return t | |
} | |
static func register<T>(dependency: T) { | |
dependencyList[String(describing: T.self)] = dependency | |
} | |
} | |
@propertyWrapper struct Inject<T> { | |
var wrappedValue: T | |
init() { | |
self.wrappedValue = DependencyInjector.resolve() | |
} | |
} | |
@propertyWrapper struct Provider<T> { | |
var wrappedValue: T | |
init(wrappedValue: T) { | |
self.wrappedValue = wrappedValue | |
DependencyInjector.register(dependency: wrappedValue) | |
} | |
} | |
struct DependencyProvider { | |
@Provider var fooService: FooService = Foo("Hello") as FooService | |
} | |
protocol FooService { | |
func printMessage() | |
} | |
class Foo: FooService { | |
private let message: String | |
init(_ message: String) { | |
self.message = message | |
} | |
func printMessage() { | |
print(message) | |
} | |
} | |
class Bar { | |
@Inject var foo: FooService | |
func useFoo() { | |
foo.printMessage() | |
} | |
} | |
DependencyProvider() | |
let bar = Bar() | |
bar.useFoo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment