Thursday, April 27, 2017

Using Swift Protocol Composition for Dependency Injection

Krzysztof Zabłocki:

Swift allows us to compose protocol requirements by using & operator, that means that our entities can now contain just a single dependency storage:

class FooViewModel {
    typealias Dependencies = HasImageProvider & HasArticleProvider
    let dependencies: Dependencies init(..., dependencies: Dependencies)

In your app controller or flow coordinator (Whatever is used to create new entities) you can store all dependencies under a single container struct:

struct AppDependency: HasImageProvider, HasArticleProvider, HasPersistanceProvider { 
    let imageProvider: ImageProvider
    let articleProvider: ArticlesProvider
    let persistanceProvider: PersistenceProvider

Now all app dependencies are stored in a simple data container, one that doesn’t have any logic, its not magical or anything, its just a plain struct.

Comments RSS · Twitter

Leave a Comment