Swift : Swinject Dependency injection

Saad El Oulladi
3 min readNov 20, 2020

Sometimes coming across some technical words seems very intimidating. But once you take your time to understand it. You discover that was only a matter of vocabulary . That was the case for me for Swinject, when i got it, i found that i was already doing my self something similar 😂.

That’s why i decided to try to explain Swinject in the most simple way in this article.

Dependency injection

⚠️ If you already know what dependency injection is and what is used for. you can skip dependency injection section to the Swinject part.

Before talking about dependency injection, let’s talk first about not doing dependency injection 😛.

Not injecting dependencies is considered to be a bad thing (A code smell). Let’s give an example and explain this step by step.

Here we have a simple Cat Model, An Api class that provides cats. and a ViewModel that uses the api.

ViewModel is using the API, we say that the API is a dependency of ViewModel.

Here the api is created inside the viewModel, Means that when when doing unit tests, there is no way to use a fake api test with. and this is not good 😊.

In the case abode we say that the Dependency is not injected.

Let’s see the next example :

Here instead of initialising the API inside the method, we have an API property we passed through the init.

Which means during unit tests, we can simply use a fake (Mock) API.

Swinject

You might be wondering, if dependency injection is possible by passing dependencies in init methods. why do we need a library for that, why do we…

--

--