Let's say you have a list of items, and you would like to iterate it item-by-item. The for loop allows the iteration of the list while providing the item and the index of its position to the list.

The structure of a for loop has as follows. It has an item  argument, and index argument and an array  argument. The item argument should be the same type as the array argument. The index  argument has Int value. The item argument represents the object of the list at the index .

For example, let's say we have an array of names the "namesList" in a "testFunction." The namesList contains four names: ["Anna", "Emily", "Maria", "Rose"]. To be able to use the for loop, we will create two function variables: one "name" string variable, and one "index" int variable. We will not initialize them since they will be set by the for loop.

We place the name variable to the item  argument of the for loop and the index variable to the index  argument. At the array we place the model variable namesList

In our case, the for loop will run four times. 

  • First time: name  = "Anna" and index  = 0
  • Second time: name   = "Emily" and index   = 1
  • Third time: name = "Maria" and index   = 2
  • Fourth time: name   = "Rose" and index  = 3
Did this answer your question?