What is a loop, and what is it used for
This is undoubtedly one of the most important parts of the content as a loop gives us the power to handle large amounts of variables or information in a very simple way.
So far, when we've shown a list of items to the user, we've had to write each one of them in our code, but what happens if we need to show 1000 items? Or 10,000? What if the user wants to add or remove an item?
To handle all of this, we can combine the use of Arrays with loops and, using the ForEach
command, display each value in our Array no matter how many items it contains or if they change over time.
Let's look at an example where we use the ScrollView
component (which is similar to ScrollView
), but this time, the content will only be a loop made with the ForEach
command.
@State var shoppingList: [String] = [
"Potatoes",
"Tomato",
"Grapefruit",
"Chicken",
"Cookies",
"Water",
"Juice",
"Salmon"
]
var body: some View {
ScrollView {
ForEach(shoppingList, id: \.self) { item in
Text(item)
}
}
}
ForEach
is just one way to create loops in our views. We will see how to create loops with other commands in upcoming articles.
On the one hand, we have an Array with all the items to display. This is just an example but this Array could come from a database, it could contain an unknown number of elements, or the user could add or remove items.
All of this is handled by the command ForEach
, which will execute the code that we wrote once per each element it finds in our Array.
Let's analyze what ForEach
needs:
shoppingList
: We specify the variable that contains the data to display.id: \.self
: Each element needs an identifier; we will see what this means later. For now, we will always use this.- Inside the curly braces
{ }
, we write the block of code that will be executed for each element of our Array. item
is a temporary variable that we are declarating (just the name is enough), and it will only be used inside the block. It contains the value of the Array element currently being executed.in
is just part of the syntax of theForEach
command; it must always be added after the temporary variable.
Using indices
We can also use a range of numbers to build our ForEach
and access the items in our array using the index:
Use ..<
to create a range of numbers that includes the number on the left and excludes the one on the right.
For example, 0..<10
will include the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
.
shoppingList.count
to create a range with the indices of our Array: 0..<shoppingList.count
.
ForEach(0..<shoppingList.count, id: \.self) { i in
Text(shoppingList[i])
}
Be the first to comment