top of page

Dependency Injection in Swift: In a nutshell

Writer's picture: Shubham BakshiShubham Bakshi

A dog getting cozy

As tough as the name “Dependency Injection” sounds, it’s a really simple and straightforward concept, and hence the quote from James Shore:

“Dependency Injection” is a 25-dollar term for a 5-cent concept

While I was reading about Dependency Injection in swift, I came across somewhat complex explanations for a topic that is pretty straight forward. I will keep this article really short on purpose because there's no complex thing about Dependency Injection that needs a lot of explanation or examples.


Consider the code that we see a lot on the daily basis:


… this is pretty much what Dependency Injection really is !


 

In case you did not understand the above piece of code, let me explain:

  1. Without Dependency Injection: This is a situation where we do not provide a way for our object (employee1) to provide data for our properties; they are all provided internally

  2. Initialiser based Dependency Injection: This is a situation where we can provide data to our properties through initialiser of the object (employee2)

  3. Property based Dependency Injection: This is a situation where we can provide data to our properties by accessing the properties of the object (employee3) directly


Advantages

  1. Ease of writing unit test cases. Real implementations can easily be substituted with mock data

  2. It provides an improved level of flexibility and decoupling between components

  3. Better maintainability, readability and reusability


That’s it, folks! Happy Coding!

Related Posts

Site's author picture

Shubham Bakshi

Been coding since '13. Rode the Apple bandwagon in '18. Some can say it was love at first byte. I engineer apps with such finesse, they practically dance through your device. And if you're a dev feeling lost in the code jungle, fear not! I'm here to be your coding compass, guiding you through the wilderness of curly braces and semicolons.

Website logo
© Bits & Bytes w/ Bakshi. All rights reserved.
bottom of page