Learning Dependency Injection using Swift
Want to make your Apps conform to the principles known as SOLID?
3 min readAug 19, 2019
In object-oriented programming SOLID is an acronym for five design principles. One of these design principles is the Dependency inversion principle. We can use this principle to create better, more testable Swift code.
Motivation
High level modules should not be dependent on low-level modules, but rather abstractions. If this is true, we can swap out classes rather than making a fixed dependency for a concrete class.
The Theory
Dependency injection requires:
- a server to be used
- a client that uses the service
- an interface between the client and service (used by the client and implemented by the service)
- an injector that creates a service instance and injects it into the client
This can then be used for mocking and testing the implementation of a server, with any particular client.
Step-by-step
A high-level class A is dependent on a specific instance of class B