SwiftData – passing context to non-views

I recently started studying SwiftData and there’s one aspect of the pattern that eludes me.

It seems quite easy to pass the model context to a view like so

MyView().modelContainer(for: MyModel.self)

And I can easily access it from MyView like so:

@Environment(\.modelContext) var ModelContext

But what happens if I don’t want to always use the view? Suppose I want to do

class StorageManager {

   private let modelContext: ModelContext

   init(modelContext: ModelContext) {
     self.modelContext = modelContext
   }
}

MyView(storageManager: StorageManager)

The issue is, I can’t seem to pass modelContext to StorageManager. The compiler complains about accessing the model context installed outside a View. “This will always read the default value and will not update” Any ideas?

  • stackoverflow.com/questions/77096233/…

    – 

You can put logic in model classes, extensions of ModelContext, custom View structs, view modifiers or dynamic properties but you shouldn’t make your own classes because you’ll get consistency bugs that Swift’s use of value types is designed to eliminate. Also if you try to init classes in body Like MyView(storageManager: StorageManager(...)) then that is a memory leak and will slow down SwiftUI.

Leave a Comment