Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift for-in Loop

Swift for-in Loop

Swift loopsSwift Loops

The Swift for-in loop is used to iterate over all elements in a collection, such as a range of numbers, elements in an array, or characters in a string.

Syntax

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



for index in var {

   循环体

}

Flow diagram:

Example 1



import Cocoa



for index in 1...5 {

    print("\(index) 乘于 5 为:\(index * 5)")

}

In the example, the elements used for iteration are a numeric range from 1 to 5 represented by the closed range operator (...). i

The output of the above program 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 is:



index 的值为 10

index 的值为 20

index 的值为 30

Swift loopsSwift Loops