Member-only story

Learning Dependency Injection using Swift

Want to make your Apps conform to the principles known as SOLID?

Steven Curtis
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

A tightly coupled system where the Client relies on the Server

In Swift this might look something like the following implementation:

The Client Class is highly dependent on the Server Class, and any changes to the Server class would likely require changes to the Client class. This tight coupling is highly discouraged.

The client is highly dependent on the service here

Dependency injection works in such a way that we can swap in another server at any point. Any server instance can be swapped out.

--

--

Responses (1)

Write a response