Last active
April 14, 2020 14:12
-
-
Save dfrobison/f2d02ce57c032305854634050866d6ae to your computer and use it in GitHub Desktop.
[Simple dependency manager] A simple dependency manager that cleans itself up completely because of using NSMapTable (https://swiftrocks.com/weak-dictionary-values-in-swift)
This file contains hidden or 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
| import Foundation | |
| final class DependencyStore { | |
| var factories = [String: () -> Dependency]() | |
| var cachedDependencies = NSMapTable<NSString, AnyObject>.init( | |
| keyOptions: .copyIn, | |
| valueOptions: .weakMemory | |
| ) | |
| func register<T: Dependency>(dependencyFactory: @escaping () -> T) { | |
| let key = T.identifier | |
| factories[key] = dependencyFactory | |
| } | |
| func getInstanceOf<T: Dependency>(dependencyType type: T.Type) -> T? { | |
| let key = T.identifier | |
| let cachedInstance = cachedDependencies.object(forKey: key as NSString) | |
| if cachedInstance != nil { | |
| print("Using old value!") | |
| return cachedInstance as? T | |
| } else { | |
| print("Using new value!") | |
| let newInstance = factories[key]?() | |
| cachedDependencies.setObject(newInstance, forKey: key as NSString) | |
| return newInstance as? T | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment