Swift for Loop
This loop method has been 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 the value of a counter after each loop completes.
Syntax
The syntax format of the Swift for loop is as follows:
for init; condition; increment{
循环体
}
Parameter explanation:
- initIt is executed first, and only once. This step allows you to declare and initialize any loop control variables. You can also write no statement here, as long as a semicolon appears.
- Next, it is evaluatedcondition. If it is true, the loop body is executed. If it is false, the loop body is not executed, and control flow jumps to the next statement immediately following the for loop.
- After the for loop body has been executed, control flow jumps back to theincrementstatement. 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 it is true, the loop executes, and this process keeps repeating (loop body, then increment the step value, then re-evaluate the condition). When the condition becomes false, the for loop terminates.
Flowchart:
Examples
import Cocoa
var someInts:[Int] = [10, 20, 30]
for var index = 0; index < 3; ++index {
print( "索引 [\(index)] 对应的值为 \(someInts[index])")
}
The above program produces the following output:
索引 [0] 对应的值为 10 索引 [1] 对应的值为 20 索引 [2] 对应的值为 30Other Extensions
Swift Loop