How to create dependency injection in swift?

Divesh Singh
2 min readNov 8, 2019

--

In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A “dependency” is an object that can be used, for example as a service. Instead of a client specifying which service it will use, something tells the client what service to use. According to Wikipedia: https://en.wikipedia.org/wiki/Dependency_injection

Dependency injection is nothing but it is style of writing code and way of constructing object where we can say yes my code is totally de-coupled and When we are testing our objects, we can easily set up unit tests and replace our dependency for another property of its type. Three-way to create it.

There is three-way to write code as dependency injection.

  1. Property injection — In this way we inject property from outside.
class CameraViewModel {
var camera = Camera?
}
let cameraViewModel = CameraViewModel()let customCamera = Camera() // Individual creationcameraViewModel.camera = customCamera // here customCamera is injecting to viewModel via property.

2. Constructor/Initializer : Inject object at the time of creation

class CameraViewModel {    var camera: Camera    init(customCamera: Camera) {        self.camera = customCamera       }
}
// Calling timelet customCamera = Camera() // Individual creationlet cameraViewModel = CameraViewModel(customeCamera) //injected by constructor

3. Via Protocol/interface Method : Inject it when call method


class
Film {
}
protocol
CameraManager {
func showInPortrate(in customCamera: Camera)}extension Film : CameraManager { func showInPortrate(in customCamera: Camera) { print(customCamera) }
}

If you find this article is helpful please do not forget to share, recommend, and clap.

--

--

Divesh Singh
Divesh Singh

Written by Divesh Singh

Postgraduate from JEC Jabalpur || iOS and macOS developer, traveler |||| EM at Darwinbox | Ex-Samsung || Ex - Optimize IT Sys | Ex - R Systems

No responses yet