Swift for-in Loop

Swift 循环Swift Loops

The Swift for-in loop is used to iterate over all elements in a collection, such as numeric ranges, elements in an array, and characters in a string.

Syntax

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

for index in var {
   循环体
}

Flowchart:

Example 1

import Cocoa

for index in 1...5 {
    print("\(index) 乘于 5 为:\(index * 5)")
}

The element iterated in the example is a numeric range from 1 to 5 represented by the closed range operator (...). i

The output of the above program execution is:

1 乘于 5 为:5
2 乘于 5 为:10
3 乘于 5 为:15
4 乘于 5 为:20
5 乘于 5 为:25

Example 2

import Cocoa

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

for index in someInts {
   print( "index 的值为 \(index)")
}

The output of the above program execution is:

index 的值为 10
index 的值为 20
index 的值为 30

Swift 循环Swift Loops

Other Extensions