Skip to content

Instantly share code, notes, and snippets.

@colinfwren
Created January 18, 2025 22:19
Show Gist options
  • Save colinfwren/dd011662402c3001301b702677e0d420 to your computer and use it in GitHub Desktop.
Save colinfwren/dd011662402c3001301b702677e0d420 to your computer and use it in GitHub Desktop.
Exposing service as an environment object
import SwiftUI
import SwiftData
@main
struct ExampleApp: App {
private let exampleService: ExampleService
let sharedModelContainer: ModelContainer
init() {
let schema = Schema([
SomeModel.self,
SomeOtherModel.self
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
sharedModelContainer = try ModelContainer(for: schema, configurations: [modelConfiguration])
exampleService = ExampleService(modelContext: sharedModelContainer.mainContext)
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(exampleService)
}
.modelContainer(sharedModelContainer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment