Vitaly Batrakov

5 min read

Jul 1, 2023

This is a cross-post from my blog. If you wish, you can go there to read it.

Press enter or click to view image in full size

In the previous articles about Dependency Injection, we learned about the importance of DI in building scalable, maintainable, and testable iOS applications. We also learned that the Factory library can be a modern solution for DI.

NOTE: In this post, I assume you are already familiar with the concept of DI (but you can learn more about it from this post).

In SwiftUI, Apple introduces a slightly different approach to DI compared to traditional UIKit development. In this article, we will explore the fundamentals of how DI works in the context of SwiftUI.

SwiftUI — two chairs for DI

We will cover two different approaches for DI we have in SwiftUI:

  • Constructor injection
  • Environment injection

Let’s consider both options more carefully.

Constructor injection

This approach should already be familiar to you from previous posts. It is a reliable and widely-used method for implementing DI, which you likely have utilized extensively in iOS development prior to the introduction of SwiftUI.

class LoginViewModel {
let authService: AuthenticationService