Por qué las vistas necesitan estado
Comprenda por qué las vistas de SwiftUI son inmutables.
Por qué las vistas necesitan estado es una lección gratuita de SwiftUI Academy en CoddyKit. Esta es la lección 1 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.
Views Describe, They Don't Hold
A SwiftUI view is a lightweight description of your UI for one moment. It is recreated constantly, so it can't simply store changing values like a normal object. 📐
Structs Are Immutable
Your views are structs, and SwiftUI treats their stored properties as read-only inside body. You cannot just reassign a property and expect the screen to react.
struct CounterView: View {
var count = 0
var body: some View {
Text("Count: \(count)")
}
}Why Reassigning Fails
Try setting a plain property from a button and the compiler stops you: structs can't mutate themselves inside body. The UI has no idea anything changed anyway.
The UI Is a Function of Data
In SwiftUI, the screen is a pure function of your data. Same data in, same UI out. To change the screen, you change the data, not the view directly.
Enter State
SwiftUI gives you state: a place to store changing values that lives outside the throwaway view struct. When state changes, SwiftUI rebuilds the affected views for you. ✨
State Survives Redraws
Even though the view struct is recreated again and again, your state value persists between redraws. SwiftUI stores it safely behind the scenes for that view.
The Source of Truth
State becomes the single source of truth for a piece of view-local data. The view always reflects it, so there is never a stale, out-of-sync screen.
A Tiny Example
Here a stored value drives the text. Once it is marked as state, changing it will automatically refresh the Text on screen.
struct GreetingView: View {
@State private var name = "Sam"
var body: some View {
Text("Hi, \(name)")
}
}Reactive, Not Imperative
You never tell a label to update itself. You change the data and SwiftUI reacts. This declarative style means less wiring and fewer bugs.
When You Need State
Use state for values a single view owns and changes over time: a counter, a toggle, typed text. Static labels and fixed config don't need it.
Keep State Small
State is meant for simple, view-local data. Keep each piece focused so SwiftUI can update efficiently and your views stay easy to reason about.
Quick Check
Why can't a SwiftUI view just store a changing value in a plain property?
Recap
SwiftUI views are immutable structs and the UI is a function of data. State lets a view own changing values that persist across redraws and drive automatic updates. 🎯
Preguntas frecuentes
¿La lección «Por qué las vistas necesitan estado» es gratis?
Sí — el texto completo de «Por qué las vistas necesitan estado» 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 «Por qué las vistas necesitan estado»?
Comprenda por qué las vistas de SwiftUI son inmutables. 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 1 de 4.
¿Cuánto tiempo toma la lección «Por qué las vistas necesitan estado»?
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
- Por qué las vistas necesitan estado
- Declaración de propiedades @State
- Creación de un contador de pulsaciones
- Alternar la visibilidad con el estado