Swift for loop, switch, while With Examples

In this tutorial, we’ll be looking into the wide variety of statements that Swift has to offer. We’ll be largely covering swift for loop, swift while, repeat-while and switch statements. Open up the playground and let’s dive right in it. Earlier we looked into Swift array. Furthermore we’ll be looking at the newly introduced One Sided Ranges with Swift 4.

If you’d like to use an online compiler for Swift, go for https://iswift.org/playground.

Swift for loop

To iterate over a sequence without using subscripts (indexes) we use for loop as shown below.


var numberArray = [2,4,6,8,10]
for number in numberArray {
    print(number)
}

for-in loops using subscripts with lower and upper bounds


var numberArray = [2,4,6,8,10]
for i in lowerbound...upperbound
{
 //do something
}
//example : 1
var numberArray = [2,4,6,8,10]
for i in 0...4
{
 print(numberArray[i])
}

The array gets iterated from the lowerbound to the upperbound (both inclusive) using closed range operator (...). To iterate with the upper bound not included, we use the half-range operator (..<). An example is given below:


for i in 0..<4
{
 print(numberArray[i]) //doesn't print 10
}

Note: If lowerbound > upperbound there’ll be a crash.
To print the array in reverse order we can use the reversed() function as shown below.


for i in (0..<4).reversed()
{
 print(numberArray[i])
}
// the below code will crash
for i in 4..<0
{
 print(numberArray[i])
}

stride is a function from the Swift library that allows us to enter the start value, end value and the offset value to increment by as shown below:


//count from 1 to 10 by 1
for i in stride(from: 1, to: 10, by: 1) {
    print(i)
}
//count from 1 to 10 by 2
for i in stride(from: 1, to: 10, by: 2) {
    print(i)
}
prints:
1
3
5
7
9

Ignoring value from each sequence

for _ in 1...5 {
    print("Hello World")
}

Underscore effectively gets rid of the value from each sequence. This usage is similar to while loop and can be used for calculating the power of a number as shown below:


let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("(base) to the power of (power) is (answer)")

While loop

while loops through it’s body of statements until the condition becomes false.


var i = 0
while i <= 5 {
    print(i)
    i = i + 1
}

Note: conditions present in all the control flow statements such as while and for-in loops, if else in Swift, unlike other languages aren’t enclosed in parentheses ().

repeat-while loops while a condition is met. The difference between a while and a repeat-while loop is that the repeat loop executes the statements present in the body before checking the condition.


var i = 5
repeat {
    print(i)
    i = i + 1
} while i < 5

Note: repeat-while loop is similar to the do-while loop in C, JAVA.

Switch statements

A switch statement considers a value and compares it against several possible matching patterns. An example is given below:


let character: Character = "a"
switch character {
case "a":
    print("The first letter of the alphabet") //this gets printed.
case "z":
    print("The last letter of the alphabet")
default:
    print("Some other character")
}

Unlike other languages switch statements in swift, finish as soon as the first case is matched. They don’t fallthrough other cases or require an explicit break statement.
To explicitly fallthrough the cases the fallthrough keyword is required as shown under:


let character: Character = "a"
switch character {
case "a":
    print("The first letter of the alphabet") //this gets printed.
    fallthrough
case "z":
    print("The last letter of the alphabet")//this gets printed too
    fallthrough
default:
    print("Some other character") //this gets printed too
}

Combining multiple cases in switch
Swift allows multiple cases to be appended in switch (separated by commas) as shown below.


var myInt = 0
switch myInt
{
case 0, 1, 2:
    print("zero, one or two") //this gets printed.
case 3,5,7:
    print("three, five or seven")
case 4:
    print("four")
default:
    print("Integer out of range")
}

Interval matching in Switch
Values in switch cases can be checked for their inclusion in a certain range as shown below:


var myInt = 5
switch (myInt)
{
case 0...5:
    print("First half") //this gets printed
case 5..<10:
    print("Second half")
default:
    print("Out of range")
}

In the above code “First Half” is printed. Though the number 5 exists in both the cases, the first is printed since its met first.
The second case ranges from 5 to 10 where 10 is not inclusive.

Using where statement


var myInt = 5
switch (myInt)
{
case 0...5 where myInt%2==0:
    print("First half only even accepted")
case 5..<10:
    print("Second half only odd accepted")
default:
    print("Out of range")
}

The where keyword is used to add an additional criteria inside the case.

One-Sided Ranges

Swift 4 has introduced one-sided ranges wherein the missing range is automatically inferred.
Following example demonstrate the same.


let stringArray = ["How", "you", "doing", "today", "??"]
let lowerHalf = stringArray[..<2] //["How", "you"]
let upperHalf = stringArray[2...] //["doing", "today", "??]

This brings an end to this tutorial. We’ve discussed and implemented all the major control statements.

By admin

Leave a Reply

%d bloggers like this: