How to create dependency injection in swift?

Divesh Singh
Nov 8 · 2 min read

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) }
}

Divesh Singh

Written by

iOS and macOS developer, traveller |||| Team Lead at Optimize IT Systems

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade