Dependency Injection using Swift Property Wrappers
Define dependencies (e.g. in AppDelegate) that need to be injected via property:
let dependencies = Dependencies {
Dependency { LocationService() }
Dependency { StorageService() }
// ...
}
Build when it's needed (e.g. in Scene willConnectTo):
dependencies.build()
Define injected properties:
@Injected var location: LocationService
@Injected var storage: StorageService
Iterate over all dependencies:
for service in dependencies {
service.start()
}
Access using dynamic member lookup:
let location: LocationProtocol? = dependencies.locationService // Erase type to protocol
let storage: StorageService = dependencies.storageService! // Force unwarp if needed
More details on implementation and usage is here
- In Xcode select File ⭢ Swift Packages ⭢ Add Package Dependency...
- Copy-paste repository URL: https://github.com/avdyushin/Injected
- Hit Next two times, under Add to Target select your build target.
- Hit Finish