Swift Loops

There are many kinds of loops available in Swift programming language like For loop, While Loop, Repeat-While loop.

For Loop

For loop is used to iterate over certain number of times.

    for idx in 1..5
	    print("Hello World")

After the execution of for loop “Hello World” will be printed 5 times.

Iterating For Loop over an Array

You can also get index and value of array by using enumerated() method of array.

    let myArray = [1,5,7,8,9,33] 
    for (idx,val) in myArray.enumerated()
	    print("At Index \(idx) : \(val)")

Iterating For Loop over Dictionary

You can also get key and value of dictionary by using enumerated() method of dictionary.

    let myDictionary = ["fb":"Facebook","t":"Twitter"] 
    for (key,val) in myDictionary.enumerated()
	    print("At Key \(key) : \(val)")

While Loop

A while loop starts by evaluating the condition. If condition is successful it executes block of statements until condition becomes false.

    var value=1
    while value<=10
        print("Current value is \(value)")
        value += 1

The while loop executes 10 times because on 10th turn, value would become 11, and condition of while loop will become false.

Repeat - While Loop

In Repeat- while loop, block of statements are executed at least once. After that it checks against condition. If condition is true then block of statements would continuously be executed until loop condition results into false.

    var myNumber = 10
	    print("This is")
	    myNumber -=1 
    while myNumber > 0

Labeled Statements

You can write nested loops as well. To exit an outer loop you can label the outer loop and write break with the label in inner loop or anywhere then control of outer loop will be broken and statement next to outer loop will start be executing.

    let x = 15
    myLabel: while x<15

In the example, while loop has a label myLabel. To break it, you can write “break myLabel”