Swift for Loop
This loop form was deprecated in Swift 3.
The 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 iteration.
Syntax
The syntax of the Swift for loop is as follows:
for init; condition; increment{
循环体
}
Parameter analysis:
- init is executed first and only once. This step allows you to declare and initialize any loop control variables. You may also write no statement here, as long as a semicolon appears.
- Next, the conditionis evaluated. If true, the loop body executes. If false, the loop body is not executed and control flow jumps to the statement immediately following the for loop.
- After executing the for loop body, control flow jumps back to the above increment statement. This statement allows you to update the loop control variable. This statement can be left empty, as long as a semicolon appears after the condition.
- The condition is evaluated again. If true, the loop executes; this process repeats (loop body, then increment step, then re-evaluate condition). The for loop terminates when the condition becomes false.
Flow diagram:
Example
import Cocoa
var someInts:[Int] = [10, 20, 30]
for var index = 0; index < 3; ++index {
print( "索引 [\(index)] 对应的值为 \(someInts[index])")
}
The output of the above program is:
索引 [0] 对应的值为 10
索引 [1] 对应的值为 20
索引 [2] 对应的值为 30
Swift Loops