Learning Dependency Injection using Swift

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

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

Step-by-step

A high-level class A would be dependent on a specific instance of class B

A tightly coupled class where the Client relies on the Server
The client is highly dependent on the service here
The client can use any particular service instance

Dependency injection in view controllers

Property-based dependency injection

If the view controller identifier in the storyboard changes, the data would silently not be passed to the view controller. This gives unexpected behaviour that is only apparent at runtime.

Initializer-based dependency injection

We can create

Conclusions

It isn’t a coincidence that dependency injection is a major principle that software developers integrate into their code.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store