0Pricing
SwiftUI Academy · Aula

Repetindo com ForEach

Renderize linhas a partir de uma matriz de dados.

Repetindo com ForEach é uma aula grátis de SwiftUI Academy no CoddyKit. Esta é a aula 2 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.

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. 🎉

Perguntas Frequentes

A aula “Repetindo com ForEach” é grátis?

Sim — o texto completo de “Repetindo com ForEach” é 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 “Repetindo com ForEach”?

Renderize linhas a partir de uma matriz de dados. 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 2 de 4.

Quanto tempo leva a aula “Repetindo com ForEach”?

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

  1. Criando uma lista estática
  2. Repetindo com ForEach
  3. Identifiable e IDs estáveis
  4. Seções e estilos de lista
← Voltar para SwiftUI Academy