Latest web development tutorials

Swift for loop

Swift cycle Swift cycle

Swift for loop is used to repeat a series of statements until certain conditions are reached, generally after each cycle is completed by increasing the value of the counter to achieve.

grammar

Swift for loop syntax is as follows:

for init; condition; increment{
   循环体
}

Analytical parameters:

  1. init is executed first, and only once.This step allows you to declare and initialize any loop control variables. You can also write any statement that is not here, as long as there is a semicolon to appear.
  2. Next, we will judgecondition.If true, the loop body is executed. If false, the loop body is not executed, and the control flow jumps to immediately for the next statement cycle.
  3. After executing the for loop body, control flow jumps back aboveincrement statement.This statement allows you to update the loop control variable. The statement can be left blank, as long as the conditions appear to have a semicolon.
  4. Condition is judged again. If true, then the execution cycle, the process is repeated (loop body, and then increase the step value, then to re-determine the conditions). When the condition becomes false, for loop terminates.

flow chart:

Examples

import Cocoa

var someInts:[Int] = [10, 20, 30]

for var index = 0; index < 3; ++index {
   print( "索引 [\(index)] 对应的值为 \(someInts[index])")
}

The above program execution output is:

索引 [0] 对应的值为 10
索引 [1] 对应的值为 20
索引 [2] 对应的值为 30

Swift cycle Swift cycle