Swift for cycle


Release date:2023-11-28 Update date:2023-12-08 Editor:admin View counts:242

Label:

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:

  1. 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.

  2. 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 following for the next statement of the loop.

  3. After the execution for after looping the body, the control flow jumps back to the increment 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.

  4. 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:

Image0

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

Powered by TorCMS (https://github.com/bukun/TorCMS).