为 ViewModel 注入依赖
注入服务,让视图模型便于测试。
为 ViewModel 注入依赖 是 CoddyKit 上的免费 SwiftUI Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.
用 AI 导师学习 Swift — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 30
- 课程
- 120
常见问题解答
「为 ViewModel 注入依赖」课时是免费的吗?
是的 — 「为 ViewModel 注入依赖」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 SwiftUI Academy 课程的其余内容,请升级到 CoddyKit PRO。 SwiftUI Academy 课程共包含 4 节课。
「为 ViewModel 注入依赖」这节课中我会学到什么?
注入服务,让视图模型便于测试。 你通过在浏览器中直接运行的动手代码来练习 SwiftUI Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 SwiftUI Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 SwiftUI Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「为 ViewModel 注入依赖」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 SwiftUI Academy 课中编写并运行代码吗?
能。每节 SwiftUI Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- MVVM 为何适合 SwiftUI
- 设计 ViewModel
- 将视图绑定到 ViewModel
- 为 ViewModel 注入依赖