Swift for Loop
>
Swift for loop is used to repeatedly execute a series of statements until a specific condition is met, typically by incrementing a counter after each loop completion.
Syntax
The syntax for a Swift for loop is as follows:
for init; condition; increment {
loop body
}
Parameter Explanation:
init is executed first and only once. This step allows you to declare and initialize any loop control variables. You can also leave this step empty, as long as a semicolon is present.
Next, the condition is evaluated. If it is true, the loop body is executed. If it is false, the loop body is not executed, and the control flow jumps to the statement immediately following the for loop.
After executing the loop body, the control flow jumps back to the increment statement. This statement allows you to update the loop control variables. This statement can be left empty, as long as a semicolon is present after the condition.
The condition is evaluated again. If it is true, the loop is executed, and this process repeats (loop body, then increment, then re-evaluate the condition). The for loop terminates when the condition becomes false.
Flowchart:
Example
import Cocoa
var someInts:[Int] = [10, 20, 30]
for var index = 0; index < 3; ++index {
print("Value at index [\(index)] is \(someInts[index])")
}
The output of the above program is:
Value at index [0] is 10
Value at index [1] is 20
Value at index [2] is 30