position: fixed; top: auto !important; margin-left: 112px;

Swift Loops

If you are familiar with programming languages like C, C++ or Java you might have heard about for loops, while loops etc. Loops are basically used to repeatedly execute the set of statements. Suppose you want to print the elements from 1 to 100, then initializing the variable 100 times is a very complicated task. So here looping of statement saves the time and helps to write simplified code.

Swift 4 supports three types of loops:

1) for in loop

2) while loop

2) repeat while loop

for in loop

for in loops through the set of statements especially while looping over arrays, looping through dictionaries, looping through nummeric ranges in swift 4.

Syntax

Basic syntax of for..in loop is given below,

for var in arrayName
{
.....
set of statements to be executed.
}

Looping over Array

let names = ["Man", "Ni", "Neha"]   
for name in names {   
    print(names)
}

Output:

Man
Ni
Neha

Looping through Range

for numbe in 1..10 {   
    print(numbe)
}

Output:

1
2
3
4
5
6
7
8
9
10

Half range operator (a..

..< operator runs from a to b, but doesn't include b. We can also use hald range operator (..<) in loops like this,

for numbe in 1..<10 {   
    print(numbe)
} 

Output:

1
2
3
4
5
6
7
8
9

As you notice loop runs from 1 to 10 but di d not included 10.

While loop

Swift while loop program executes set of statements repeatedly if the condition is true. Following example will illustrate how to use while loop in swift 4,

import Foundation 

var x = 0
while x < 5 { 
    print ("\(x)")  //prints x until x < 5 evaluates to false
    x = x + 1
}

Output:

0
1
2
3
4

Swift Repeat-While Loop

Swift repeat-while loop is similar to do-while loop in other programming languages like C, C++, Java etc. In swift, repeat-while loop is similar to while loops, but the only difference is repeat while executes statement at least once apart from its condition testing scenario.

 import Foundation 

var summation = 1
repeat
{
print(summation)
summation = summation + 1
} while summation < 10

Output:

1
2
3
4
5
6
7
8
9

Previous Next Article







codzify.com


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Linkedin
Twitter
Facebook

Copyright 2018. All rights reserved.