How to do Swift Dependency Injection Parameter Based
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
3. Parameter Based
We already covered Initializer Based Swift Dependency Injection and Parameter Based Swift Dependency Injection . In this blog we will focus on Parameter Based Swift Dependency Injection. Parameter based Dependency Injections is suitable for static classes where our static class method/api can't have initializers. Our api calls can have some internal dependencies. Let's take a look at example of that.
If you see above FileUploader's class the static method/api calls has two internal dependency. To make this api call easily testable we need to be able to pass dependency from outside. Considering this function/api being static we can't have initializer, this is where parameter based dependency injection comes handy. We can modify the api call/function to take dependency as parameter. Let's take a look how it looks after the change.
So by making this minor change we made our upload api call easily testable/mockable. We can go a step forward and make default arguments for the api call.
Conclusion
After covering different options for dependency injection in swift, whats the one option that we should always use?. I would say it depends on your use case. There is no one size fits all thing. I would love to hear your comments on dependency injections and your use cases.
Thanks for reading!