Introduction to Swift | Control Statements | Repetition with for

Swift provides several forms of loops. The most commonly used one is the for statement, which has two forms.

Basic Form of for-in

for variableName in collection {
    ... repeated processing ...
}

Use this form to iterate over a collection of values such as an array or range. Write a variable name after for, then an array or range after in. Add the repeated processing inside braces.

The loop retrieves values sequentially and assigns each one to the variable. For example, write the following to use values from 1 through 10.

for index in 1...10 {...}

When the retrieved value is not needed, use an underscore (_) as the variable name.

for _ in 1...10

This creates a loop that repeats ten times.

Basic Form of for

for initialization; condition; post-processing {
    ... repeated processing ...
}

Use this form when you need more detailed control over repetition. It has three elements.

Element Description
Initialization Processing performed before the loop begins.
Condition Checked on every iteration. Continue when true; exit when false.
Post-processing Processing performed after each iteration before the next one begins.

This form is familiar from many other languages. Usually, it initializes a variable and increments or decrements that value after each iteration.

for var i = 0; i <10; i ++ {
    "index :"+ String (i)
}

This code initializes i and repeats while counting from 0 toward 10. String(i) converts the value to text.

For simple counting, a range with for-in is easier to read. The advantage of this form is that you can freely define the condition and post-processing, such as increasing a variable by two on each iteration.