Dependency Injection in Swift

Updated 12 December 2023

Save
Dependency Injection in Swift

Dependency Injection is a technique where one object supplies the dependency of another object.

Dependency Injection is used to write loosely coupled code. Using dependency injection in our code, we are giving an instance variable to an object.

The main objective of Dependency injection is that instead of creating the dependency internally an object can retrieve it from the outside.

Now, instead of giving our object the responsibility of creating its own dependency, we inject the dependencies to the object instead.

There are below types of Dependency injections

  1. Property Injection
  2. Constructor Injection
  3. Method Injection

Property Injection

Let’s understand with the help of code

In the above example we have a DemoViewModel which carries and instantiates the property and creating it’s own dependency.

Let’s take another example

Here, the view model object is not creating its own dependency. The dependency is injected into the view model via demo property and is receiving it from outside.

Constructor Injection

Another type of Dependency injection is constructor injection where the dependency is injected into an object right at its inception.

Let’s take the example of constructor injection.

As we can see the entire view model can be initialize through one property, hence the dependency is located at constructor part.

We generally prefer constructor injection because it prevents us from using an object that is not  fully configured.

Method Injection

As the name suggests in method injection dependencies are injected through methods.

Let’s take below example

Here we can see protocol has a method on its own that can takes in an injected dependency.

I hope you got brief idea about Dependency Injection in Swift.

Thanks for reading 🙂

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home