Loops I
What is a loop? The loop ForEach.
Loops I
What is a loop? The loop ForEach.
0
0
Checkbox to mark video as read
Mark as read

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)
        }
    }
}

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 the ForEach 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:

ForEach(0..<shoppingList.count, id: \.self) { i in
    Text(shoppingList[i])
}

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy