From 322910496fcc44489235f5ae3085cd8afc486268 Mon Sep 17 00:00:00 2001 From: dankito Date: Wed, 15 Jul 2020 22:48:29 +0200 Subject: [PATCH] Added DependencyInjector as simple dependency injection framework --- .../BankingiOSApp/ui/DependencyInjector.swift | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 ui/BankingiOSApp/BankingiOSApp/ui/DependencyInjector.swift diff --git a/ui/BankingiOSApp/BankingiOSApp/ui/DependencyInjector.swift b/ui/BankingiOSApp/BankingiOSApp/ui/DependencyInjector.swift new file mode 100644 index 00000000..bcf5fdae --- /dev/null +++ b/ui/BankingiOSApp/BankingiOSApp/ui/DependencyInjector.swift @@ -0,0 +1,25 @@ +/** + Code copied from Hannes Hertach, https://medium.com/@hanneshertach/swiftui-dependency-injection-in-20-lines-b322457065a5 + */ +struct DependencyInjector { + private static var dependencyList: [String:Any] = [:] + + static func resolve() -> 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(dependency: T) { + dependencyList[String(describing: T.self)] = dependency + } +} + +@propertyWrapper struct Inject { + var wrappedValue: T + + init() { + self.wrappedValue = DependencyInjector.resolve() + } +}