How to do Swift Dependency Injection Property Based

Shashank Thakur
2 min readAug 21, 2020

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

We already covered Initializer Based Swift Dependency Injection here. In this blog we will focus on Property Based Swift Dependency Injection. Property based Dependency Injections is suitable for system classes where you don’t necessarily have access to initialization. For eg a view controller initiated by Storyboard or XIB where we don’t have control over initialization. In this case we can just initialize the property later on. Lets look at an example

If you see above ViewController’s property fileManager and networkManager are initialized after instance is created. We can go step ahead and also do default value too.

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

--

--