Dependency injection in Swift with Examples

Lakshmi K
2 min readFeb 23, 2022

--

Dependency injection in simple words it means, instead of giving our object of responsibility to create it’s own depenedency we will inject dependency to object.

With dependency injection we can write loosely coupled code and test the code easly.

We have 3 types of dependency injections

  1. Property Injection
  2. Constructor Injection
  3. Method Injection
  4. Property Injection: We will inject creation of property instead of allowing class to create it’s own dependency ,

let’s see an example of a class creating it’s own dependency and property dependency injection

class Car {

var owner = CarOwner() // #1 — This is normal declaration , where object is itself responsbile for creating dependency

var secondOwner : CarOwner?

}

let audi = Car()

audi.secondOwner = CarOwner() // #2 — here we are injecting dependency to object

class CarOwner {

var name : String?

}

in the above example ,#1- if Car class itself creating object of CarOwner then we can say the code is tightly coupled. but at #2 we are taking the responsibility of assigning CarOwner to secodOwner object.

2. Constructor Injection: If we inject dependency at the time of creating constructors then we will call it constructor injection , below is the example

class StudentLibrary {

var library: Library

init(library: Library) {

self.library = library

}

}

class Library {

}

In the above example , while writing init method we are passing Library class and assigning in it.

3. Method Injection: If we inject dependency at the time of method declaration and calling then it is Method injection, below is the example

class LibraryManager {

func deleteAllBooks(in library: Library) {

}

}

Note : Main benfit of dependency injection is Our class object have responsibility of managing and handling dependency instead of creating it by itself.

I hope I explained what Dependency Injection is along with examples , if any questions please do leave a comment. Happy Coding & Reading :)

--

--