Swift for cycle
This loop has been deprecated in Swift 3.
Swift for
a loop is used to repeat a series of statements until a specific condition is reached, usually by increasing the value of the counter after each loop is completed.
Grammar
Swift for
the syntax format of the loop is as follows:
for init; condition; increment{
loop body
}
Parameter resolution:
init
will be executed first, and only once. This step allows you to declare and initialize any loop control variables. You can also not write any statements here, as long as a semicolon appears.Next, it will judge
condition
. If true, the loop body is executed. If false, the loop body is not executed, and the control flow jumps to the followingfor
the next statement of the loop.After the execution
for
after looping the body, the control flow jumps back to theincrement
statement. This statement allows you to update loop control variables. This statement can be left blank as long as a semicolon appears after the condition.The conditions are judged again. If true, the loop is executed, and the process is repeated over and over again (loop body, then increase the step value, and then re-determine the condition). The for loop terminates when the condition becomes false.
Flow chart:
Example
import Cocoa
var someInts:[Int] = [10, 20, 30]
for var index = 0; index < 3; ++index {
print( "The value corresponding to the index [\(index)] is \(someInts[index])")
}
The output of the above program execution is as follows:
The value corresponding to index [0] is 10
The value corresponding to index [1] is 20
The value corresponding to index [2] is 30