English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn about for-in loops, with examples and variants.
for-in loops to run a set of tasks within a certain amount of time. These loops iterate over any sequence, such as items in an array, a range, or characters in a string.
We also use for-in loop to execute some repetitive processes in a fixed amount of time.
Imagine someone tells you to write a program that outputs Hello, World!on the screen! Your solution will be:
print("Hello, World!")
What if they change their mind and tell you to write a program that outputs Hello, World!on the screen five times? If you don't know about loops, your solution might be:
print("Hello, World!") print("Hello, World!") print("Hello, World!") print("Hello, World!") print("Hello, World!")
Well, completing five similar pieces of code to do the same work can be time-consuming. If that's the case, if someone asks you to write a program that outputs Hello, World!on the screen hundreds or even millions of times? What will you do?
A naive solution is to write print statements for the given number of times. Sounds crazy, right? But by using for-A few lines of code in the in loop can find a better solution:
for i in 1...100 { //Output Hello World on the screen 100 times print("Hello, World!") }
Don't worry about the syntax, we will discuss it below.
You can create a for in loop in Swift as follows:
for <value> in <range> { <some work here> }
The above loop iterates over a range, and we can access each element returned from the range in the <value> variable. If you are not familiar with ranges, you can check the following article:Swift Ranges.
The sequence being iterated is a <range>.
Sets <value> to the first number in the range and executes the statement < Some work here >
After the statement is executed, <value> is updated to contain the second value in <range>, and the statement <Some work here> is executed again.
This process continues until it reaches the end of the range and stops the loop.
for i in 1...3 { print("Hello world!. Value is \(i)") }
When the program is run, the output is:
Hello world!. Value is 1 Hello world!. Value is 2 Hello world!. Value is 3
In the above program, the range of the sequence to be iterated is1to3.
The value of i is set to the range (1). The first number in the range is updated to the next number in the range in each iteration. This process continues until the range (3. The end of the range (
Iteration | The value returned from the range (i) | Output |
---|---|---|
1 | 1 | Hello world!. Value is 1 |
2 | 2 | Hello world!. Value is 2 |
3 | 3 | Hello world!. Value is 3 |
If the range value is not used within the loop, you can use the underscore _ to discard in Swift, as shown below:
for _ in <range> { <some work here> }
//This example ignores the value and uses the half-open range operator for _ in 1..<3 { print("Hello world!") }
When the program is run, the output is:
Hello world! Hello world!
In the above program, due to the use ofhalf-open range operator(.. <),so the range of the sequence to be traversed is1to2which includes the lower limit (1) but does not include the upper limit (3)。
the underscore _ ignores the range (1), and execute the print statement. Call the print statement again for the next iteration, and the process ends because2is the last value in the range.
Iteration | from the range returned | Output |
---|---|---|
1 | Discard | Hello world! |
2 | Discard | Hello world! |
If you want the loop to increment by a fixed value (instead of a range) at each iteration, you must use the stride method.
let interval = 2 for i in stride(from: 1, to: 10, by: interval) { print(i) }
When the program is run, the output is:
1 3 5 7 9
In the above program, the stride function returns a number sequence:1、3、5、7、9.
i's value is set to the sequence (1) of the first number, and execute the print statement within the loop, which outputs " 1"
After executing this statement, update the value of i to another value (3), and call the print statement again. This process continues until all elements in the sequence are accessed.
Value | Condition (Value < End) | i (output) |
---|---|---|
1 | 1 < 10 (true) | 1 |
1 + 2 = 3 | 3 < 10 (true) | 3 |
1 + 2 * 2 = 5 | 5 < 10 (true) | 5 |
1 + 3 * 2 = 7 | 7 < 10 (true) | 7 |
1 + 4 * 2 = 9 | 9 < 10 (true) | 9 |
1 + 5 * 2 = 11 | 11 < 10 (false) | Stops |
Suppose you have an array of strings, as shown below. If you are not familiar with arrays, you can consider them as a single container that can store multiple values. For more detailed explanations, please seeSwift Array.
let programmingLanguages = ["Swift", "Java", "Go", "JavaScript", "Kotlin", "Python"]
What should you do if someone tells you to print all programming languages?
One method is to use the index value programmingLanguages[0], programmingLanguages[1]... to access these elements, and so on, until all elements are obtained. But this is too cumbersome.
So the loop comes in handy. You can use the for-in loop for iteration:
let programmingLanguages = ["Swift", "Java", "Go", "JavaScript", "Kotlin", "Python"] for language in programmingLanguages { print(language) }
When the program is run, the output is:
Swift Java Go JavaScript Kotlin Python
In the above program, the sequence to be iterated is an array of strings.
The value of language is set to the first element of the array, and the print statement inside the loop is executed, which outputs "Swift" in the console.
After the statement is executed, the value of language will be updated to the next element in the array, and the print statement will be called again. This process continues until the last element of the array is accessed.
Since in SwiftStringis also a collection, so you can use a for loop to access each character in the string.
for value in "I♥Swift!" { print(value) }
When the program is run, the output is:
I ♥ S w i f t !
If you want to access the index (the position of the element in the array, i.e., 0,1、2),then you need to use the enumerated method:
let programmingLanguages = ["Swift", "Java", "Go", "JavaScript", "Kotlin", "Python"] for (index, language) in programmingLanguages.enumerated() { print("\(index):\(language)") }
When the program is run, the output is:
0:Swift 1:Java 2:Go 3:JavaScript 4:Kotlin 5:Python
Here, the enumeration method returns a tuple (Int, String) consisting of the index (Int) and value (String) of each item in the array. For example: (0,Swift), (1,Java)
Using for-loop, you can access these items in the tuple. If you are not familiar with Tuple, you can simply think of it as a container that can hold different types of values.
You can also usewhereThe clause filters out the content inside the for loop
for value in "I♥Swift!" where value != "!" { print(value) //Delete the exclamation mark }
When the program is run, the output is:
I ♥ S w i f t
In the above program, the sequence to be iterated is a string (a set of characters).
value is set to the first character of the string, and it is checked using the where condition. If the condition returns true, the block inside the loop (print statement) will be executed, which outputs "I" in the console.
After the statement is executed, value will be updated to the next character of the string, and the condition will be checked again. If the condition returns false, the block will not be executed, and value will be updated to the next character.
This process continues until the last character of the string is accessed.
Iteration | value | value != "!" | Output |
---|---|---|---|
1 | I | true | I |
2 | ♥ | true | ♥ |
3 | S | true | S |
4 | w | true | w |
5 | i | true | i |
6 | f | true | f |
7 | t | true | t |
8 | ! | false |