How to use ForEach in SwiftUI to create views

If we want to create views from an array of data then ForEach in SwiftUI helps us to iterate over the array and generate view for each element in it.

Suppose we want to create 6 views in a VStack. We can use close range from 0…5 as parameter in ForEach for this purpose and we have to provide the id as ‘\.self’ otherwise we get an error. SwiftUI needs the identity for each element so it can know which item is deleted or added.

Create views with close range

var body: some View {
        VStack {
            ForEach(0...5, id: \.self){ index in
                Text("View \(index)")
            }
        }
    }

In this case each value from range has become identity of the element.

Create views with data array

In other case suppose we have an array of strings and we want to use each value of array as content of the view inside the ForEach then we can provide array as data parameter and ‘\.self’ for each element’s identity.

let data = ["First Item", "Second Item", "Third Item"]
    
    var body: some View {
        VStack {
            ForEach(data, id: \.self){ item in
                Text(item)
            }
        }
    }

Create views with custom data model

If you have some custom type objects array like ‘FifaGoals’ with properties id, goals and teamName. We will assign UUID for unique identification to the id property of each item after conforming to the Identifiable protocol.

struct FifaGoals: Identifiable {
    let id = UUID()
    let goals: Int
    let teamName: String
}

Now we can create a loop of views with the help of ForEach using following piece of code:

let goals = [
        FifaGoals(goals: 3, teamName: "Brazil"),
        FifaGoals(goals: 4, teamName: "Argentina"),
        FifaGoals(goals: 5, teamName: "Italy")
    ]
    
    var body: some View {
        VStack {
            ForEach(goals){ item in
                HStack {
                    Text(item.teamName)
                    Spacer()
                    Text(item.goals.description)
                }.padding(20)
                 .background(.green)
            }
        }
    }

Now the ForEach struct will not require id parameter as we have already assigned UUID to the id property.

SwiftUI ForEach with Index

Sometimes we need index also inside the ForEach. For this purpose we can use range from 0 to size of data array. In this way we get index and we can retrieve each element of array using this index. We have to provide the ‘\.self’ value to id parameter otherwise it shows warning. Now the ForEach will look like:

ForEach(0..<goals.count, id:\.self){ index in
                HStack {
                    Text(goals[index].teamName)
                    Spacer()
                    Text(goals[index].goals.description)
                }.padding(20)
                 .background(.green)
            }

In short we saw how to loop through an array or use range to create views. With range we get index which is useful in many cases.

Leave a Reply

Your email address will not be published. Required fields are marked *