Swift for-in Loop
In Swift, a for-in
loop is used to iterate over a sequence, such as an array, range, or string. The loop performs a set of statements for each item in the sequence.
The basic syntax of a for-in
loop in Swift is as follows:
1for item in sequence { 2 // statements 3}
Here, item
is a variable that is used to represent each item in the sequence, and sequence
is the sequence over which the loop is iterating. The statements inside the loop are executed for each item in the sequence.
Using a for-in loop with an array
One of the most common uses of a for-in
loop in Swift is to iterate over an array. Here's an example:
1let numbers = [1, 2, 3, 4, 5] 2for number in numbers { 3 print(number) 4}
Output:
11 22 33 44 55
In this example, the for-in
loop iterates over an array of integers named numbers
. For each integer in the array, the loop prints the number to the console.
Using a for-in loop with a range
You can also use a for-in
loop to iterate over a range of values. Here's an example:
1for index in 1...5 { 2 print(index) 3}
Output:
11 22 33 44 55
In this example, the for-in
loop iterates over a range of integers from 1 to 5. For each integer in the range, the loop prints the number to the console.
Using a for-in loop with a string
You can also use a for-in
loop to iterate over a string. Here's an example:
1let message = "Hello, world!" 2for character in message { 3 print(character) 4}
Output:
1H 2e 3l 4l 5o 6, 7 8w 9o 10r 11l 12d 13!
In this example, the for-in
loop iterates over a string named message
. For each character in the string, the loop prints the character to the console.
Using the enumerated() method
Sometimes you may want to access both the index and value of each item in a sequence. You can use the enumerated()
method to achieve this. Here's an example:
1let numbers = [1, 2, 3, 4, 5] 2for (index, number) in numbers.enumerated() { 3 print("Item \(index): \(number)") 4}
Output:
1Item 0: 1 2Item 1: 2 3Item 2: 3 4Item 3: 4 5Item 4: 5
In this example, the for-in
loop iterates over an array of integers named numbers
. The enumerated()
method returns a sequence of tuples, each containing an index and a value. The loop then prints out each index and value to the console.
Using the stride() method
The stride()
method can be used to create a sequence of values with a given step. Here's an example:
1for i in stride(from: 0, to: 10, by: 2) { 2 print(i) 3}
Output:
10 22 34 46 58