Compartilhando Modelos via @Environment
Injete um modelo no ambiente da visualização.
Compartilhando Modelos via @Environment é 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.
Sharing Down Many Levels
Passing a model through every view in between gets tedious. The environment lets deep child views reach it directly.
What the Environment Is
The environment is a shared bag of values flowing down the view tree, so any descendant can read what an ancestor placed there.
Injecting with .environment
Place an observable model into the tree with the .environment modifier on a parent view.
ContentView()
.environment(model)Reading with @Environment
A child reads the shared model by declaring a property with the @Environment wrapper and the model type.
@Environment(Counter.self) private var modelMatching by Type
The environment finds the model by its type, so the type you inject must match the type a child asks for.
No Manual Passing
Children no longer need the model handed through every initializer. They simply pull it from the environment when needed.
Using the Shared Model
Once read, the environment model behaves like any other: read its values and call its methods.
Text("\(model.count)")
Button("Add") { model.increment() }One Instance, Many Readers
Everyone reads the same injected instance, so changes made in one screen show up everywhere that reads it.
Inject Once, High Up
Inject the model near the top of the tree, often at the app root, so every screen below can share it.
WindowGroup {
RootView().environment(model)
}Owner Still Uses @State
One view still owns the model with @State and injects it. The environment only shares that single instance downward.
Missing Model Crashes
If a child reads a model the environment never received, the app crashes, so always inject before any reader appears.
Quick Check
Final check on sharing through the environment.
Recap
You shared one model across the view tree using @Environment: inject it high up, then read it by type in any descendant. 🌍
Perguntas Frequentes
A aula “Compartilhando Modelos via @Environment” é grátis?
Sim — o texto completo de “Compartilhando Modelos via @Environment” é 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 “Compartilhando Modelos via @Environment”?
Injete um modelo no ambiente da visualização. 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 “Compartilhando Modelos via @Environment”?
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
- Do Estado da Visualização para uma Classe de Modelo
- A Macro @Observable
- @State para Objetos de Propriedade
- Compartilhando Modelos via @Environment