How to do Swift Dependency Injection with Initializers

Swift Dependency Injection

Dependency Injection feel like a very complicated topic but in fact it is very simple. We as devs all try to follow design principle like SOLID so that our code is properly structured in a modular way and not a spaghetti code. Dependency injection really help with this. It also helps in mocking/testing our code.

Dependency injection literally means injecting the dependency. In programming world it means injecting the dependencies our code needs in order to work. There are three flavors of dependency injection in Swift

1. Initializer Based
2. Parameter Based
3. Property Based

In this blog we will focus on Initializer Based Dependency Injection. Lets take a look at this example 




If you look at the example above, FileUploader instance initialization is dependent on file manager and network manager. So this is a very tightly coupled code.  We can use initializer based Swift Dependency Injection to make this a little better


So this subtle change makes a huge difference, instead of hardcoding file manager and network manager in the init method of FileUploader we are passing the required/dependency as parameters externally. This is basically what dependency injection is. We will talk about other flavors of dependency injection in coming articles.

 



Popular posts from this blog

How to make an iOS App Secure?

System Design Interview For Mobile Engineers

How to make iOS app secure from screenshot and recording?