0Pricing
SwiftUI Academy · Lección

Inyección de dependencias para ViewModels

Inyecte servicios para mantener los view models fáciles de probar.

Inyección de dependencias para ViewModels es una lección gratuita de SwiftUI Academy en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de SwiftUI Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de SwiftUI Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «Inyección de dependencias para ViewModels» es gratis?

Sí — el texto completo de «Inyección de dependencias para ViewModels» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de SwiftUI Academy, actualiza a CoddyKit PRO. El curso de SwiftUI Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Inyección de dependencias para ViewModels»?

Inyecte servicios para mantener los view models fáciles de probar. Practicas SwiftUI Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar SwiftUI Academy?

No se requiere experiencia previa. SwiftUI Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Inyección de dependencias para ViewModels»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de SwiftUI Academy?

Sí. Cada lección de SwiftUI Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Por qué MVVM encaja con SwiftUI
  2. Diseñar un ViewModel
  3. Vincular vistas a ViewModels
  4. Inyección de dependencias para ViewModels
← Volver a SwiftUI Academy