Only the image is generated with chatgpt

Member-only story

Share data in a SwiftUI application

Nicola De Filippo
2 min readMay 17, 2024

Many blog posts are responses to my students’ questions, and this one is no different. Often, my students need to build fast prototypes without saving permanent data and want to avoid writing complicated code with Core Data or the newer SwiftData. They frequently ask, “How can we share data across the application without passing it as a parameter to every view?” The answer is to use an EnvironmentObject.

Definition

First, let’s define the object that we want to share:

struct Event: Identifiable {
var id = UUID()
var name: String
}

class Shared: ObservableObject {
@Published var events: [Event] = [Event]()
}

The shared object will be a class, marked as ObservableObject (allowing us to catch changes), with the events array being the published property. In this case, we have only one array, but there’s no limit to the number of properties that can be published.

Usage

After defining the class, we need to declare a variable of the shared class using @StateObject. Then, we pass this variable to the .environmentObject modifier. These steps are performed in just one view—the root view of any other views that will use the shared object.

struct ContentView: View {
@State var isPresented = false
@StateObject…

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

Nicola De Filippo
Nicola De Filippo

Written by Nicola De Filippo

Software Engineer and Entrepreneur

No responses yet

Write a response