Guide for Dependency Injection in Swift

How to Do Swift Dependency Injection With Initializers

Types of Dependency Injection in Swift

Shashank Thakur
The Startup

--

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. Property Based
  3. Parameter 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.

Originally published at https://www.shashankthakur.dev.

--

--