We use the for-in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string.
Using For In loop with Simple Array:
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, (name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
Using For In loop with Dictionary:
We can also iterate over a dictionary to access its key-value pairs.
Each item in the dictionary is returned as a (key, value) tuple when the dictionary is iterated.
We can decompose the (key, value) tuple’s members as explicitly named constants for use within the body of the for-in loop.
Let's take a look at example:
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("(animalName)s have (legCount) legs")
}
// cats have 4 legs
// ants have 6 legs
// spiders have 8 legs
In the code example below, the dictionary’s keys are decomposed into a constant called animalName, and the dictionary’s values are decomposed into a constant called legCount.
The contents of a Dictionary are inherently unordered, and iterating over them does not guarantee the order in which they will be retrieved. In particular, the order you insert items into a Dictionary doesn’t define the order they are iterated.
Using for-in loops with numeric ranges:
Foe example:
for index in 1...5 {
print("(index) times 5 is (index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
In the example above, index is a constant whose value is automatically set at the start of each iteration of the loop. As such, index does not have to be declared before it is used. It is implicitly declared simply by its inclusion in the loop declaration, without the need for a let declaration keyword.
The sequence being iterated over is a range of numbers from 1 to 5, inclusive, as indicated by the use of the closed range operator (…).
The value of index is set to the first number in the range (1), and the statements inside the loop are executed. In this case, the loop contains only one statement, which prints an entry from the five-times table for the current value of index. After the statement is executed, the value of index is updated to contain the second value in the range (2), and the print(_:separator:terminator:) function is called again. This process continues until the end of the range is reached.
Using for-in loops with closed ranges:
In some situations, you might not want to use closed ranges, which include both endpoints.
Consider drawing the tick marks for every minute on a watch face. You want to draw 60 tick marks, starting with the 0 minute. Use the half-open range operator (..<) to include the lower bound but not the upper bound.
For example:
let minutes = 60
for tickMark in 0..<minutes {
// render the tick mark each minute (60 times)
}
basics for loop loop