- Learn Swift by Building Applications
- Emil Atanasov
- 284字
- 2021-06-25 22:13:47
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.
- Mastering Adobe Captivate 2017(Fourth Edition)
- 零基礎學MQL:基于EA的自動化交易編程
- 高級C/C++編譯技術(典藏版)
- Instant QlikView 11 Application Development
- 微信公眾平臺開發:從零基礎到ThinkPHP5高性能框架實踐
- 軟件架構:Python語言實現
- Learning Selenium Testing Tools(Third Edition)
- Julia高性能科學計算(第2版)
- PrimeFaces Blueprints
- 后臺開發:核心技術與應用實踐
- Java Web開發實例大全(基礎卷) (軟件工程師開發大系)
- Mastering Adobe Captivate 7
- Simulation for Data Science with R
- Modernizing Legacy Applications in PHP
- Learning Bootstrap 4(Second Edition)