Thursday, April 27, 2017 [Tweets] [Favorites]

Using Swift Protocol Compositon 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.


Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment