Swift: Inversion of Control

Karthik
2 min readAug 13, 2021

--

This post is all about swift inversion of control and how to make use of it in real-time.

Inversion of Control:

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code. This Principle helps in designing loosely coupled classes that make them testable, maintainable, and extensible.

If you follow these simple two steps, you have done the inversion of control:

  1. Separate the what-to-do part from the when-to-do part.
  2. Ensure that when part knows as little as possible about what part; and vice versa.

ContactService: Without IoC

Assume we have a contact service class responsible for fetching contacts from the server and storing them in the database. Without dependency injection, the contact service class looks like

Classes that help to fetch and store the contacts.
ContactService.swift

Line no 6, and 7 creates a strong dependency on creating the contact service object. which tends to lose control over the contactsApi and database object. Here comes dependency injection to rescue.

ContactService: With IoC

With the dependency injection principle, contactsApi and Database object injection while contact service objection creation.

Now contact service class has control over which ContactsApi implementation to use because we’re injecting the dependency into the ContactService signature.

Conclusion

Some of the examples help to elevate the dependency injection to that make code testable, maintainable, and extensible.

  • Dependency Injection. Code that constructs a dependency (what-to-do part) — instantiating and injecting that dependency for the clients when needed, which is usually taken care of by the DI tools such as Swinject (when-to-do-part).
  • Interfaces. Component client (when-to-do part) — Component Interface implementation (what-to-do part)
  • Template Design Pattern. Template method when-to-do part — primitive subclass implementation what-to-do part

Note: MVVM + Swinject would be a great combo for managing dependency in swift. personally, we are using this pair for dependency management.

That’s it for this time! 👏👏👏 . Feel free to comment if you have questions and follow to get notifications about future articles.

“Be the senior engineer you needed as a junior.” — Someone

--

--