- Learn Swift by Building Applications
- Emil Atanasov
- 284字
- 2025-04-04 16:55:54
Loops
Let's learn how to implement repetitive tasks. There are several ways to do that, using different loops: while, for...in, and repeat...while. The most popular one is the for...in loop. Here is what the basic form looks like:
let collection = [1, 2, 3]
for variable in collection {
//do some action
}
The code will be interpreted like this: the variable will be set to all possible values, which are stored in the collection. If the collection is empty, then no code will be executed. If there are some elements, then the body of the loop (the code in curly braces) will be executed for each element of the collection. The variable loops through every single element and can be used in code.
We need an example to illustrate this. Let's use the following code to print all numbers from 1 to 10, inclusive:
var sum = 0
for index in 1...10 {
sum += index
print("(index)")
}
print("Sum: \(sum)")
//sum is equal to 55
The sum of all numbers from 1 to 10 is stored in a separate variable and the code prints every single number on a new line. The sequence defined with 1...10 is converted to a collection (we can think of it as an array), which is fueling the for...in loop.
We can use variables or constants to define custom ranges of numbers.
Take a look at the following code:
let threeTimes = 3
for _ in 1...threeTimes {
print("Print this message.")
}
Using _ (underscore) we declare that the argument should ignore the values set in the variable, and it doesn't matter to the rest of the code. The code will print three times: Print this message.