Looping with for loops
for
loops allow you to execute code for each element in a collection or range. In this recipe, we will explore how to use for
loops to perform actions on every element in a collection.
Getting ready
In this recipe, we won’t be using any components from the previous recipes, so you can create a new playground for this recipe.
How to do it...
Let’s create some collections and then use for
loops to act on each element in the collection:
- Create an array of elements so that we can do something with every item in the array:
let ledZeppelin = ["Robert", "Jimmy", "John", "John Paul"]
- Create a loop to go through our theBeatles array, and print each string element that the for loop provides:
for musician in ledZeppelin {
print(musician)
}
- Create a for loop that executes some code a set number of times, instead of looping through an array. We can do this...