0Pricing
SwiftUI Academy · Lección

@State para objetos propios

Gestione un modelo observable con @State.

@State para objetos propios es una lección gratuita de SwiftUI Academy en CoddyKit. Esta es la lección 3 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.

Who Owns the Model

An observable model needs an owner: a view that creates it and keeps it alive for as long as the screen exists.

@State Owns the Instance

Use @State to let a view own an observable model. The view creates it once and holds onto it across redraws.

@State private var model = Counter()

Why @State Here

Without @State, a fresh model would be made on every redraw, wiping your data. @State persists the same instance.

Reading the Model

Read tracked properties straight from the model in your body, and the view refreshes when they change.

Text("Count: \(model.count)")

Calling Model Methods

Trigger behaviour by calling the model methods from your controls, keeping the view free of the actual logic.

Button("Add") { model.increment() }

Mark It private

Keep owned state private so other types cannot reach in and mutate the model behind the view back.

@State private var model = Counter()

No $ to Read

To read an observable model you use it directly. The dollar sign $ is only for making a binding, which we cover later.

A Full Owned View

Here a view owns the model, reads its value, and updates it on tap, all in one tidy place.

struct CounterView: View {
    @State private var model = Counter()
    var body: some View {
        Button("\(model.count)") { model.increment() }
    }
}

Survives Redraws

Because @State is managed by SwiftUI, your model survives every body re-evaluation while the view is on screen.

One Owner Rule

A model should have a single owner. Child views receive access instead of each making their own copy.

Lifetime Tied to the View

The model lives as long as its owning view. When the view leaves the screen for good, the model is released.

Quick Check

Let us confirm how ownership works.

Recap

You used @State to let a view own its observable model, so a single instance survives redraws while the view reads and updates it. ✨

Preguntas frecuentes

¿La lección «@State para objetos propios» es gratis?

Sí — el texto completo de «@State para objetos propios» 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 «@State para objetos propios»?

Gestione un modelo observable con @State. 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 3 de 4.

¿Cuánto tiempo toma la lección «@State para objetos propios»?

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. Del estado de la vista a una clase de modelo
  2. La macro @Observable
  3. @State para objetos propios
  4. Compartir modelos mediante @Environment
← Volver a SwiftUI Academy