Type Eraser for Containers

Hi all,

Is this allowed:

environment(\.container, MyContainer() as Any)

While injecting Model container into the environment we use Type . Is there any universal injection type that can inject container as set of any types rather than array similar to navigationPath() type-eraser ?

You've left a lot of context out, so I'm not quite sure what you're asking. You might have more luck asking on the Apple developer forums, since I think this might be specific to Apple's platform frameworks.

1 Like

I apologise for the oversight. I’m referring to the injection of a model container into the environment. We accomplish this by declaring the type as follows:

swift

.modelContainer(for: [Book.self, Author.self])

For instance:

swift

@main
struct Example: App {
    @State private var appData = ApplicationData.shared

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(appData)
                .modelContainer(for: [Book.self, Author.self])
        }
    }
}

I was wondering if we could implement a feature similar to the navigationPath() type-erasing functionality. This allows us to define a heterogeneous set of types, as we can do with:

swift

@State private var path = NavigationPath()

Instead of explicitly declaring:

swift

@State private var path = [Book]()

Is there a way to build ( if not already a way) into Swift Language a similar capability for environment injection, enabling the injection of a heterogeneous set of types without needing to declare the type explicitly?

You'll probably have better luck asking over at Apple Developer Forums since your question is about Apple's SDKs.

Although Swift undoubtedly is tightly connected with Apple and their platforms, it is also a stand-alone project which supports many non-Apple platforms. This forum is about Swift as a language and compiler, its features, and future directions.

For questions about how to program applications using Swift on Apple platforms, the Apple Developer site is better suited.