Simple dependency injection library for swift projects.
Basically SwiftDI
works as Service locator. It stores
all dependencies inside own list. But Injector
can be easily splited into submodules to reduce code linking.
// Swift
let injector = Injector()
injector.bind(ApiProtocol.self)
.with { return RestApi() }
injector.bind(RepositoryProtocol.self)
.with { (api: ApiProtocol) -> RepositoryProtocol.self in
return Repository(api: api)
}
// or you can bind Repository constructor directly
injector.bind(RepositoryProtocol.self)
.with(Repository.init(api:))
// Swift
class Controller: UIViewController {
var injector: Injector! = ... // provide injector to VC
var repository: RepositoryProtocol!
func viewDidLoad() {
super.viewDidLoad()
repository = injector.resolve()
}
}
// Swift
injector.bind(ApiProtocol.self) // link with type
.tag("some tag") // link with custom string tag
.scope(.singleton) // define dependency as singleton
.with { ... } // initilization dependency closure
injector.resolve(ApiProtocol.self, tag: "some value") //resolving by type and tag
Injector
support modularization and could have isollated submodules that know about parent but don't know about siblings.
// Top level module
let injector = Injector()
injector.bind(RepositoryProtocol.self)
.with { injector -> RepositoryProtocol.self in
return Repository()
}
// Screen module
let childInjector = injector.plus()
childInjector.bind(PresenterProtocol.self)
.with { injector -> PresenterProtocol in
return Presenter(repository: injector.resolve())
}
CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. For setup you have to visit their website.
Once you have set up your project for CocoaPods you can specify SwiftDI
dependency in your Podfile
:
pod 'SwiftDI', '~> 2.0'
The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.
Once you have your Swift package set up, adding SwiftDI
as a dependency is as easy as adding it to the dependencies value of your Package.swift
:
dependencies: [
.package(url: "https://github.com/achernoprudov/SwiftDI.git", from: "2.0.0")
]