ViewModelの依存性注入
テスト可能なViewModelにするためサービスを注入します。
「ViewModelの依存性注入」はCoddyKit上の無料SwiftUI Academyレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSwiftUI Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 SwiftUI Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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.
よくある質問
「ViewModelの依存性注入」レッスンは無料ですか?
はい。「ViewModelの依存性注入」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、SwiftUI Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 SwiftUI Academyコースには全4レッスンが含まれています。
「ViewModelの依存性注入」で何を学びますか?
テスト可能なViewModelにするためサービスを注入します。 ブラウザで直接実行するハンズオンコードでSwiftUI Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
SwiftUI Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのSwiftUI Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「ViewModelの依存性注入」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このSwiftUI Academyレッスンでコードを書いて実行できますか?
はい。すべてのSwiftUI Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- MVVMがSwiftUIに適している理由
- ViewModelを設計する
- ビューをViewModelにバインドする
- ViewModelの依存性注入