For the love of loops
For loops allow you to execute code for each element in a collection or range.
How to do it...
Take a look at the following steps and code:
- Let's imagine that we have an array of elements, and we want to do something with every item in the array:
let theBeatles = ["John", "Paul", "George", "Ringo"]
- We can use a
for
loop, which will extract each element of the array in turn, and will execute the given block of code for each element. The syntax of afor
loop is as follows:
for <#each element#> in <#collection or range#> { <#code to execute#> }
- So, to print all the musicians in the Beatles, let's loop through our
theBeatles
array and print each String element that thefor
loop provides:
for musician in theBeatles { print(musician) }
- Perhaps you don't need to loop through an array, and just want to execute some code a set number of times. We can do this by providing a range instead of a collection:
// 5 times table for value in 1...12 { print...