Swift - Statement Loops

Introduction

Loops repeats a task a number of times.

When you have a collection of items, such as an array, you can use a for-in loop to iterate over every item:

Demo

let loopArray = [1,2,3,4,5,6,7,8,9,10] 
var sum = 0 /*from  w  w  w  .  j a v  a  2 s  . c  om*/
for number in loopArray { 
       sum += number 
} 
print(sum) // 55

Result

You can use a for-in loop to iterate over a range of values. For example:

Demo

// resetting our counter to 0 
var sum = 0 /*from ww  w  .j  a  v a 2s.  c  o  m*/
for number in 1  ..< 10 { 
       sum += number 
} 
print(sum) // 45

Result

The ..< operator is a range operator.

Swift uses it to describe a range of numbers from one value to another.

There are actually two range operators: two dots and a left angle bracket ..< and three dots and no angle bracket ...

The half-range operator <.. means a range that starts at the first value and goes up to but does not include the last value.

For example, the range 5..<9 contains the numbers 5, 6, 7, and 8.

To create a range that does include the last number, you instead use the closed-range operator ...

The range 5...9 contains the numbers 5, 6, 7, 8, and 9.

You can use an inclusive range operator in for-in loops like so:

Demo

// resetting our counter to 0 
var sum = 0 //w  w w . j  av a  2 s. c  o  m
for number in 1  ... 10 { 
       sum += number 
} 
print(sum) // 55

Result

The stride function precisely controls how you iterate over a sequence.

For example, say you wanted to iterate between 0 and 1, going up by 0.1 each time:

Demo

var mySum  : Double = 0 
for number in stride(from: 0, to: 1, by: 0.1) { 
       mySum += number //from  w  w w.j  a  va 2  s  .  co m
} 
print(mySum) // 4.5

Result

This is the stride(from: to: by:) form, which is exclusive of the final number.

There is an inclusive form, stride(from: through: by:):

Demo

// resetting our counter 
var mySum = 0.0 //from w  w  w .  jav  a2 s .  com
for number in stride(from: 0, through: 1, by: 0.1) { 
       mySum += number 
} 
print(mySum) // 5.5

Result

Loop such as for (int i = 0; i <= 10; i++) used to exist back in Swift 2 but was dropped along with the ++ and -- operators when Swift 3 came out.