0Pricing
SwiftUI Academy · Lección

Insertar, actualizar y eliminar

Modifique el almacén y refleje los cambios en tiempo real.

Insertar, actualizar y eliminar 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.

Changing Your Data

Now you will change the store: add new records, edit existing ones, and remove what you no longer need. ✏️

Inserting a Record

Create an object and call insert on the context to add it. SwiftData starts tracking it for saving right away.

let task = Task(title: "Walk dog")
context.insert(task)

Insert Then Appears

After an insert, any @Query view shows the new row at once. You do not refresh the list yourself.

Updating a Property

To edit a record, just change its property on the tracked object. SwiftData notices and saves the new value.

task.isDone = true

No Special Edit Call

There is no separate update method. Because the object is tracked, direct assignment is the whole update flow.

task.title = "Walk the dog twice"

Deleting a Record

Remove an object with delete on the context. It disappears from the store and from every query view.

context.delete(task)

Deleting from a List

Wire up swipe-to-delete with onDelete, then call delete for each index. Users remove rows with a familiar gesture.

.onDelete { offsets in
    for i in offsets {
        context.delete(tasks[i])
    }
}

Saving the Changes

SwiftData autosaves, but you can call save to commit immediately. It is wise before the app might close.

try context.save()

Batch Operations

Loop over a set of objects to insert or delete many at once. The context batches the work efficiently for you.

for t in finished {
    context.delete(t)
}

Handling Errors

Wrap a manual save in do-catch so a failure does not crash your app. You can warn the user instead.

do { try context.save() }
catch { print(error) }

Changes Flow to the UI

Every insert, edit, and delete reflects live in your views. The store and screen stay perfectly in step.

Quick Check

Quick check on editing data.

Recap: Editing Data

You can now insert, edit by assignment, and delete records, with the UI updating live. You have full control over your SwiftData store. 🚀

Preguntas frecuentes

¿La lección «Insertar, actualizar y eliminar» es gratis?

Sí — el texto completo de «Insertar, actualizar y eliminar» 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 «Insertar, actualizar y eliminar»?

Modifique el almacén y refleje los cambios en tiempo real. 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 «Insertar, actualizar y eliminar»?

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. Definir tipos @Model
  2. El contenedor y el contexto del modelo
  3. Consultar con @Query
  4. Insertar, actualizar y eliminar
← Volver a SwiftUI Academy