Swift - For-In Loop

Introduction

Swift supports a new loop statement known as the For-In loop.

The For-In loop iterates over a collection of items such as an array or a dictionary as well as a range of numbers.

The following code snippet prints out the numbers from 0 to 9 using the For-In loop:

for i in 0...9 {
    print(i)
}

The closed ranged operator represented by ... defines a range of numbers from 0 to 9 (inclusive).

The i is a constant whose value is initially set to 0 for the first iteration.

After executing the statement(s) in the For-In loop as defined by the {}, the value of i is incremented to 1, and so on.

Because i is a constant, you are not allowed to modify its value within the loop, like this:

Demo

for i in 0...9 {
    i++   //this is not allowed as i is a constant
    print(i)/*from   w  ww.j  a va 2 s . c om*/
}

You can use the For-In loop to output characters in Unicode, like the following:

Demo

for c in 65 ... 90 {
  print(Character(UnicodeScalar(c)))  //prints out 'A' to 'Z'
}

The UnicodeScaler is a structure that takes in an initializer containing the number representing a character in Unicode.

You then convert it to a Character type.

Related Topics