Dependency Injection für ViewModels
Injizieren Sie Services, damit ViewModels testbar bleiben.
Dependency Injection für ViewModels ist eine kostenlose SwiftUI Academy-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des SwiftUI Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der SwiftUI Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
The Hidden Dependency Problem
If a ViewModel creates its own network client inside itself, tests are stuck hitting the real server. That tight coupling makes it hard to swap later.
Inject Instead of Create
Dependency injection means passing in what a ViewModel needs from outside, rather than letting it build those services itself.
Define a Service Protocol
Describe the work with a protocol, not a concrete type. The ViewModel depends on the abstraction and never on a specific implementation.
protocol TaskService {
func fetch() async -> [Task]
}Accept It in the Initializer
Take the dependency through the init. Now any object that conforms to the protocol can be handed to the ViewModel.
init(service: TaskService) {
self.service = service
}Use the Injected Service
Inside methods, call the stored service rather than a hardcoded client. The ViewModel no longer cares who actually does the work.
tasks = await service.fetch()A Real Implementation
Your production type conforms to the protocol and talks to the network. You inject it when building the real screen.
struct LiveTaskService: TaskService {
func fetch() async -> [Task] { [] }
}A Mock for Tests
For tests, write a mock that returns fixed data instantly. Inject it to verify ViewModel logic without any real network calls.
struct MockTaskService: TaskService {
func fetch() async -> [Task] { sample }
}Tests Become Trivial
With a mock injected, a test just calls a method and checks the result. No waiting, no flakiness, only fast and predictable runs. ✅
A Default for Convenience
Give init a default real service so everyday code stays short, while tests can still override it with a mock when needed.
init(service: TaskService = LiveTaskService())Injecting via the Environment
For app-wide services, pass them through SwiftUI @Environment instead of every initializer, keeping call sites clean.
The Payoff
Injection makes ViewModels flexible and isolated. You can swap real, fake, or offline services without touching the view at all.
Quick Check
Why depend on a protocol instead of a concrete service?
Recap: Dependency Injection
You learned to inject services through a protocol, swap real for mock in tests, and even use @Environment for shared dependencies. That completes MVVM.
Häufig gestellte Fragen
Ist die Lektion „Dependency Injection für ViewModels“ kostenlos?
Ja — der vollständige Text von „Dependency Injection für ViewModels“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des SwiftUI Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der SwiftUI Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Dependency Injection für ViewModels“?
Injizieren Sie Services, damit ViewModels testbar bleiben. Du übst SwiftUI Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um SwiftUI Academy zu starten?
Keine Vorkenntnisse erforderlich. SwiftUI Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Dependency Injection für ViewModels“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser SwiftUI Academy-Lektion Code schreiben und ausführen?
Ja. Jede SwiftUI Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Warum MVVM zu SwiftUI passt
- Ein ViewModel entwerfen
- Ansichten an ViewModels binden
- Dependency Injection für ViewModels