How do I inject dependencies cleanly in SwiftUI with Swift?

Injecting dependencies in SwiftUI can be done cleanly using the Environment and EnvironmentObject features provided by SwiftUI. This allows for a flexible and maintainable architecture, especially when building complex applications. Here’s an example of how to implement dependency injection in SwiftUI.

struct UserSettings { var username: String } class UserSettingsViewModel: ObservableObject { @Published var settings = UserSettings(username: "Guest") } struct ContentView: View { @EnvironmentObject var userSettings: UserSettingsViewModel var body: some View { VStack { Text("Hello, \(userSettings.settings.username)!") } } } @main struct MyApp: App { @StateObject private var userSettings = UserSettingsViewModel() var body: some Scene { WindowGroup { ContentView() .environmentObject(userSettings) } } }

keyword1 keyword2 keyword3