How do you implement dependency injection in a SwiftUI application?
Instruction: Describe a method for injecting dependencies into SwiftUI views, and explain its benefits.
Updated
Official answer
Use initializer injection when a view's dependency should be explicit, and environment injection for a genuinely shared dependency that would otherwise pass through many layers. Decide who owns the object and how changes are observed; passing a reference alone is not the same as observing it.
This complete SwiftUI view module uses ObservableObject for compatibility with older deployment targets. The parent owns the model with StateObject, and the child observes the supplied instance:
import SwiftUI
import Combine
@MainActor final class UserModel: ObservableObject {
@Published var name: String
init(name: String) { self.name = name }
}
@MainActor struct UserView: View {
@ObservedObject var model: UserModel
var body: some View {
TextField("Name", text: $model.name)
.textFieldStyle(.roundedBorder)
.padding()
}
}
@MainActor struct UserRoot: View {
@StateObject private var model = UserModel(name: "Jane")
var body: some View { UserView(model: model) }
}
A preview or test can supply a separate UserModel with known state. For replaceable service behavior, inject a small protocol or function into the model; this example injects model state and does not pretend to implement a network service.
With EnvironmentObject, supply the matching object on an ancestor using environmentObject and declare the consumer accordingly. A missing required object is a runtime configuration failure, so wire previews and alternate navigation roots too. Environment access is convenient but makes dependencies less visible at the call site.
For iOS 17 and later, Observation provides an alternative using Observable models, State ownership, Environment lookup and Bindable where bindings are needed. Do not interchange those wrappers mechanically with ObservableObject wrappers. Check deployment availability, identity changes and the ownership lifetime; initialization of a StateObject is tied to its container identity, not every view initializer call.
Observed input models, Owned model lifetime, EnvironmentObject requirements, Observation in SwiftUI
Related Questions
-
medium
-
medium
-
hard