Better Programming

Advice for programmers.

Follow publication

Member-only story

Why You Shouldn’t Use @EnvironmentObject in SwiftUI

Riccardo Cipolleschi
Better Programming
Published in
8 min readNov 29, 2021
Photo by Agung Raharja on Unsplash

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Riccardo Cipolleschi
Riccardo Cipolleschi

Written by Riccardo Cipolleschi

Hey there, I’m Riccardo. Software engineer at Meta. I have a passion for iOS and I love to share my knowledge with others.

Write a response