Member-only story
Why You Shouldn’t Use @EnvironmentObject in SwiftUI
Shortcomings of the default SwiftUI dependency injection mechanism
One of the main topics to master to create scalable and maintainable applications is Dependency Injection. SwiftUI comes with a comfortable API for injecting dependencies: the EnvironmentObject
API, composed of a property wrapper and a view modifier.
Despite these APIs being very comfortable, they have several limitations that make them not suitable for big applications. The main shortcomings are that:
- They make it hard to program against interfaces.
- They make it hard to write tests.
In today’s article, we will explore what is an EnvironmentObject
, we will dive deeper into the limitations and we try to explore how to overcome them.
EnvironmentObject in Practice
Using the @EnvironmentObject
property wrapper is the basic approach suggested by Apple when we have to share objects between views. Usually, we want to share dependencies: objects that perform operations required by multiple parts of our applications.
Let’s create a basic setup to play with the EnvironmentObject
API. For this article, I created a simple PIDecimalGenerator
that generates the…