0Pricing
SwiftUI Academy · Lesson

Dependency Injection for ViewModels

Inject services to keep view models testable.

Dependency Injection for ViewModels is a free SwiftUI Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the SwiftUI Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

Is the “Dependency Injection for ViewModels” lesson free?

Yes — the full text of “Dependency Injection for ViewModels” is free to read here on the web, and the SwiftUI Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the SwiftUI Academy course, upgrade to CoddyKit PRO.

What will I learn in “Dependency Injection for ViewModels”?

Inject services to keep view models testable. You practise SwiftUI Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start SwiftUI Academy?

No prior experience is required. SwiftUI Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Dependency Injection for ViewModels” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this SwiftUI Academy lesson?

Yes. Every SwiftUI Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Why MVVM Fits SwiftUI
  2. Designing a ViewModel
  3. Binding Views to ViewModels
  4. Dependency Injection for ViewModels
← Back to SwiftUI Academy