Swift for-in cycle


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

Label:

Swift for-in cycle

Swift for-in loops are used to traverse all the elements in a collection, such as intervals represented by numbers, elements in an array, and characters in a string.

Grammar

Swift for-in the syntax format of the loop is as follows:

for index in var {
   loop body
}

Flow chart:

Image0

Example 1

import Cocoa

for index in 1...5 {
    print("\(index) multiplying by 5 is:\(index * 5)")
}

The element used for traversal in the example is a numerical range from 1 to 5 represented by the closed interval operator (…).

The output of the above program execution is as follows:

Multiplying 1 by 5 is: 5
Multiplying 2 by 5 is: 10
Multiplying 3 by 5 is: 15
Multiplying 4 by 5 is: 20
Multiplying 5 by 5 is: 25

Example 2

import Cocoa

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

for index in someInts {
   print( "The value of index is \(index)")
}

The output of the above program execution is as follows:

The value of index is 10
The value of index is 20
The value of index is 30

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