Dependency Injection in SwiftUI

Dependency Injection in SwiftUI

There are different ways to do dependency injection in SwiftUI. In this post, we'll look at two of them:

[…]

@EnvironmentObject allows us to inject dependencies because it looks for its value in the SwiftUI environment. This means that a view deep in the hierarchy can access a dependency without its parent passing it through.

[…]

We can call ViewModelFactory at the top level of our SwiftUI application, be it the App or UIWindowSceneDelegate implementation, to get the view models for the root views.

@EnvironmentObject trades runtime-safety for conciseness and is a more text-book SwiftUI approach, but it can crash your app.

[…]