0Pricing
SwiftUI Academy · Lección

Bucles con ForEach

Muestre filas a partir de una matriz de datos.

Bucles con ForEach es una lección gratuita de SwiftUI Academy en CoddyKit. Esta es la lección 2 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.

Why ForEach

Hardcoding rows works for two items, but real data lives in arrays. ForEach builds one row per element automatically. 🔁

let fruits = ["Apple", "Pear", "Kiwi"]

ForEach Inside List

Drop a ForEach inside a List and it generates one row for every item in your collection, no matter how many there are.

List {
    ForEach(fruits, id: \.self) { fruit in
        Text(fruit)
    }
}

The Closure Gives You Each Item

The closure runs once per element, handing you that item so you can build its row from real data.

ForEach(fruits, id: \.self) { fruit in
    Text(fruit)
}

Identity Matters

SwiftUI needs to tell rows apart, so ForEach always wants a way to identify each element uniquely.

The id Parameter

For simple value arrays, pass id set to a key path like .self so each value can identify itself uniquely to SwiftUI.

ForEach(scores, id: \.self) { score in
    Text("\(score)")
}

Looping a Range

Need a fixed count instead of an array? Pass a range and ForEach hands you each index in turn, perfect for placeholder rows.

ForEach(0..<5) { index in
    Text("Row \(index)")
}

Building Rich Rows

Inside the closure you can return any view, so each ForEach row can be a full HStack with icons and labels.

ForEach(fruits, id: \.self) { fruit in
    HStack {
        Image(systemName: "leaf")
        Text(fruit)
    }
}

Mixing Static and Dynamic

A List can hold a static header Text and a ForEach loop together, blending fixed and data-driven rows.

List {
    Text("Fruits")
    ForEach(fruits, id: \.self) { Text($0) }
}

Looping Structs

When you loop an array of structs, each item carries multiple fields you can show across the row.

ForEach(people, id: \.name) { person in
    Text(person.name)
}

Data Drives the UI

Change the array and the rows follow right along. With ForEach, your list is simply a live mirror of whatever data you give it.

Beyond Lists

ForEach is not just for lists. It also fills VStack, HStack, and grids with repeated views from any collection.

VStack {
    ForEach(fruits, id: \.self) { Text($0) }
}

Quick Check

Recall what the ForEach closure receives.

Recap

You learned ForEach: it turns any collection into rows, handing you each item so your UI tracks your data automatically. 🎉

Preguntas frecuentes

¿La lección «Bucles con ForEach» es gratis?

Sí — el texto completo de «Bucles con ForEach» 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 «Bucles con ForEach»?

Muestre filas a partir de una matriz de datos. 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 2 de 4.

¿Cuánto tiempo toma la lección «Bucles con ForEach»?

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. Creación de una lista estática
  2. Bucles con ForEach
  3. Identifiable e identificadores estables
  4. Secciones y estilos de lista
← Volver a SwiftUI Academy