Member-only story
The Service Locator Pattern in Swift
Avoid Dependency Injection entirely!

The service locator pattern is designed to encapsulate the processes invovled in obtaining a service with a strong layer of abstraction.
Prerequisites:
- You will be expected to be aware how to make a Single View Application, or a Playground to run Swift code
- This article avoids Dependency Injection, but you should be aware of what that is
- This article refers to the Singleton pattern
The explanation
Service locator has a central registry known as the service locator, that on request returns the data required to perform a task. The service locator returns instances of services when they are requested by the service consumers or service clients.
The Service Locator pattern does not describe how to instantiate serveices, rather it describes a way to register services and locate them.

The Example
Here is an example. This example is written with a Playground in mind: In fact the tests are included (and will work ina Playground).
What is happening here is that we are using a Dictionary to register services. These services can be added or removed from the list, and basically lets us “get” the services from this dictionary.
Advantages and Disadvantages
Advantages:
— Applications optimize themselves by adding or removing items from the ServiceLocator
— The only link between parts of the application becomes the registry of services
Disadvantages:
— The registry itself can be difficult to maintain
— When dependencies are missing there may be run-time errors
In fact it is common to set up the service locator itself as a Singleton…