# SwiftUI: the ForEach view

> Learn how to use the ForEach view in SwiftUI to loop over a range or an array and generate views, including how the id parameter identifies each item.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2021-09-23 | Topics: [Swift](https://flaviocopes.com/tags/swift/) | Canonical: https://flaviocopes.com/swiftui-foreach/

The `ForEach` view in SwiftUI is very useful to iterate over an array, or a range, and generate views that we can use.

For example, here we create 3 `Text` views that print the numbers from 0 to 2:

```swift
ForEach(0..<3) {
    Text("\($0)")
}
```

> $0 means the first argument passed to the closure, which in this case it's (in order) the number 0, 1, and 2.

In this example I embed them in a `VStack` otherwise they would overlap:

```swift
VStack {
    ForEach(0..<3) {
        Text("\($0)")
    }.padding()
}
```

![VStack with ForEach displaying numbers 0, 1, 2 vertically with padding](https://flaviocopes.com/images/swiftui-foreach/Screen_Shot_2021-09-22_at_18.08.15.png)

> Notice how I used the `padding()` modifier to add some spacing

A common way to use `ForEach` is inside a `List` view:

```swift
List {
    ForEach(0..<3) {
        Text("\($0)")
    }
}
```

![List view with ForEach displaying numbers 0, 1, 2 as separate rows](https://flaviocopes.com/images/swiftui-foreach/Screen_Shot_2021-09-22_at_18.15.49.png)

This is such a common thing to do that we can actually omit `ForEach` and iterate directly from `List`:

```swift
List(0..<3) {
    Text("\($0)")
}
```

![List directly iterating over range displaying numbers 0, 1, 2 as rows without explicit ForEach](https://flaviocopes.com/images/swiftui-foreach/Screen_Shot_2021-09-22_at_18.18.07.png)

Those 2 examples used a range `0..<3`. We can iterate over an array too:

```swift
let fruits = ["Apple", "Pear", "Orange"]

//...

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

![List with ForEach iterating over fruits array displaying Apple, Pear, Orange as separate rows](https://flaviocopes.com/images/swiftui-foreach/Screen_Shot_2021-09-22_at_18.28.34.png)

Notice how in this case we have another parameter: `id`.

This is to uniquely identify the item in the array. 

Using `\.self` for `id` works for built-in types, in case you are iterating a custom struct you'll need that to conform to the `Identifiable` protocol or provide a unique parameter.
