Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to pass an array using enviromentObject

I have an array of MyItem.

var array:[MyItem]

I was expecting that to fail, but I have tried to pass array using

.environmentObject(array)

Obviously it failed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Instance method ‘environmentObject’ requires that ‘[MyItems]’ conform to ‘ObservableObject’

Is there a way to do that?

>Solution :

Wrap the array inside a class conform ObservableObject, and then you can pass it normally

final class ModelData: ObservableObject {
    ....
    //Add @Published to enable binding to any views using this property
    @Published var array: [MyItem] = []
}

@StateObject private var modelData = ModelData()

var body: some Scene {
    WindowGroup {
        ContentView()
            .environmentObject(modelData)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading