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.
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 we can do something with every item in the array:
let theBeatles = ["John", "Paul", "George", "Ringo"]
- Create a loop to go through our theBeatles array and print each string element that the for loop provides:
for musician in theBeatles {
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 by providing a range instead of a collection:
// 5 times table
for value in 1...12 {
print("5 x \(value) = \(value*5)")
}
- Create a for loop to print the keys and values of a dictionary. Dictionaries contain...