Menu
Coddy logo textTech

ForEach

Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 29 of 50.

ForEach creates one view for each element of a collection:

let fruits = ["Apple", "Banana", "Cherry"]

var body: some View {
    VStack {
        ForEach(fruits, id: \.self) { fruit in
            Text(fruit)
        }
    }
}

The closure receives each element and returns its view. SwiftUI needs a way to tell the rows apart, so it asks for an id. id: \.self uses the value itself, which works when every element is different.

A range of numbers works too, with no id:

ForEach(1..<4) { number in
    Text("Row \(number)")
}

This shows Row 1, Row 2 and Row 3: 1..<4 stops before 4.

challenge icon

Challenge

Easy

Show the menu: inside the VStack, use ForEach to make one Text for each drink in drinks, in order.

Try it yourself

import SwiftUI

@main
struct CoddyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction to SwiftUI

Practice on your own: Swift playground