0Pricing
SwiftUI Academy · Aula

Injeção de Dependências para ViewModels

Injete serviços para manter os modelos de visualização testáveis.

Injeção de Dependências para ViewModels é uma aula grátis de SwiftUI Academy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de SwiftUI Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de SwiftUI Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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.

Perguntas Frequentes

A aula “Injeção de Dependências para ViewModels” é grátis?

Sim — o texto completo de “Injeção de Dependências para ViewModels” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de SwiftUI Academy, atualize para CoddyKit PRO. O curso de SwiftUI Academy inclui 4 aulas no total.

O que vou aprender em “Injeção de Dependências para ViewModels”?

Injete serviços para manter os modelos de visualização testáveis. Você pratica SwiftUI Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar SwiftUI Academy?

Nenhuma experiência prévia é necessária. SwiftUI Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Injeção de Dependências para ViewModels”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de SwiftUI Academy?

Sim. Cada aula de SwiftUI Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Por que MVVM se Adapta ao SwiftUI
  2. Projetando um ViewModel
  3. Vinculando Visualizações a ViewModels
  4. Injeção de Dependências para ViewModels
← Voltar para SwiftUI Academy