I did some research, trying to find out what this was all about and how I could use it within The Swift code base. I found that it was a concept that originates from Scala, which is based on the concept that “one should only inject via an interface (protocol), not concrete class”.
Lets get to the CODE
We will start by creating a struct which will be our model. This will hold our data that we will be receiving.
We then create a protocol that will define our repository. This protocol will have a method that will fetch all of our products for us.
Now we will need some kind of implementation for our repository. We will create a ProductRepositoryImplementation struct, that will conform to our ProductRepository protocol. In this implementation we will just return some dummy products.
This is where the magic happens
Lets create another protocol and name it ProductsRepositoryInjectable. On this protocol, lets add a property of type ProductsRepository and make this a read only property. We will now create a protocol extension, that will provide us with a default implementation for this property. This being the ProductRepositoryImplementation we created earlier.
At this point, we have just achieved dependency injection and we have not used any third party libraries. Just pure Swift. What makes this so powerful, is that we can now swop out the implementation at anytime and where we are injecting this protocol will not need to change.
So, how would we use this might be the next question? Well lets create a viewmodel where we can inject the ProductsRepositoryInjectable. Within the init, we will use our injected property and loop through each product and printing the name and cost.
Why is this useful? It makes your code more loosely coupled, testable and reusable. These are all concepts we want when writing clean code.
Go try it and let me know what you think. If you have any questions, please leave them in the comments below.
Get in Touch!
Powered by WPeMatico
Gurupriyan is a Software Engineer and a technology enthusiast, he’s been working on the field for the last 6 years. Currently focusing on mobile app development and IoT.