Control Structure

Swift provides all the familiar control flow statements from C-like languages. These include for, for-in,  while, if,  guard,  switch, break and continue.

For loops

There are two types of for loop in swift first one is  for-in  and second is  simple for loop.

  1. The forin loop performs a set of statements for each item in a sequence.

  2. The for loop performs a set of statements until a specific condition is met, typically by incrementing a counter each time the loop ends.

The simple format for for-in is as follows

for anyVariable in 1range {
print(“the value in anyvariable is \(anyvariable)”)
}

The value of anyVariable  in for-in is constant and it takes the value in between 1 to the range inclusive.

simple for loop is same as it is written in C.

for  var i=0; i<10; i++ {
print(“hello”)
}

If you don’t need the value of variable in for loop you can ignore it writing like this

for _ in 110 {
print(“hello friends”)
}

The screenshot of these three for loop is given below.

Screen Shot 2016-02-21 at 8.42.53 PM
Image: ScreenShots

for-in can be used to iterate on elements of dictionary for example.

var animals=[“Cow”: 8, “human” : 2, “ant”: 6 ]
 for (name, nooflegs) in animals{
print(“Animal \(name) has \(nooflegs) legs”)
}

Note : In for-in loop, if you iterating on dictionary the output order may be different. It is because dictionary is inherently unordered.

 

The illustration of for loop for all types discussed above can be downloaded here

While loop

while loop performs a set of statements until a condition becomes false. There are two types of while loop.

  1. while evaluates its condition at the start of each pass through the loop.

  2. repeatwhile evaluates its condition at the end of each pass through the loop.

while condition {
statements
}

While loop test the condition if condition is true the statements written get executed. This process keeps on going till the condition gets false.

repeat {

statements

} while Condition

repeat-while is used at the place of do-while in C programming.

Screen Shot 2016-02-22 at 4.22.13 PM

While loop program

While loop example can be downloaded from here

Condition Statements

There are two way for branching : if and switch. if is used to branch based on simple condition whereas switch is used for more complex conditions. if condition structure is as follows

if condition {

Statements

}

if-else structure:

if condition {

statements

} else if condition {

statements

} else {

statements

}

An Example:

var a = 72
if a <= 32 {
print(“It’s cool”)
} else if a >= 86 {
print(“It’s really hot”)
}

Switch

switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully. A switch statement provides an alternative to the if statement for responding to multiple potential states.

In its simplest form, a switch statement compares a value against one or more values of the same type:

There are some specific properties related to switch :

  1. Every switch statement consists of multiple possible cases, each of which begins with the case keyword
  2. The body of each switch case is a separate branch of code execution.
  3. Every switch statement must be exhaustive. That is, every possible value of the type being considered must be matched by one of the switch cases
  4. If no case matches write in default case.

let anotherCharacter: Character = “w”
switch anotherCharacter {
case “a”,”b”,”c”:
print(“hello”)
case “A”:
print(“The letter A”)
default:
print(“Not the letter A”)
}

No Implicit Fallthrough

In contrast with switch statements in C and Objective-C, switch statements in Swift do not fall through the bottom of each case and into the next one by default. Instead, the entire switch statement finishes its execution as soon as the first matching switch case is completed, without requiring an explicit breakstatement. This makes the switch statement safer and easier to use than in C, and avoids executing more than one switch case by mistake.

The body of each case must contain at least one executable statement. It is not valid to write the following code, because the first case is empty:

 

let anotherCharacter: Character = “w”
switch anotherCharacter {
case “a”:
case “A”:
print(“The letter A”)
default:
print(“Not the letter A”)
}

Note: Multiple matches for a single switch case can be separated by commas, and can be written over multiple lines if the list is long:

Interval Matching

Values in switch cases can be checked for their inclusion in an interval. This example uses number intervals to provide a natural-language count for numbers of any size: for example:

Screen Shot 2016-02-23 at 6.53.04 AM

In the above example, anotherNumber is evaluated in a switch statement. Each case compares that value to a number or interval. It falls in range of 5..<10, therefore output is helooo3.

Brief description :

  1. The continue statement tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop.
  2. The break statement ends execution of an entire control flow statement immediately. The break statement can be used inside a switch statement or loop statement when you want to terminate the execution of the switchor loop statement earlier than would otherwise be the case.
  3. When used inside a loop statement, break ends the loop’s execution immediately, and transfers control to the first line of code after the loop’s closing brace (}).
  4. When used inside a switch statement, break causes the switch statement to end its execution immediately, and to transfer control to the first line of code after the switch statement’s closing brace (}).

Example for continue:

Screen Shot 2016-02-24 at 6.29.26 AM

Code for the same is here

Break

The break statement ends execution of an entire control flow statement immediately. The break statement can be used inside a switch statement or loop statement when you want to terminate the execution of the switchor loop statement earlier than would otherwise be the case.

  1. When used inside a loop statement, break ends the loop’s execution immediately, and transfers control to the first line of code after the loop’s closing brace (}).
  2. When used inside a switch statement, break causes the switch statement to end its execution immediately, and to transfer control to the first line of code after the switch statement’s closing brace (}).
  3. If you want to ignore a particular case in switch, use break as you can’t leave a case without statement. Therefore, break is the option to use

Screen Shot 2016-02-24 at 7.03.53 AM

The illustration of break is given in the screenshot above.

Example of break can be downloaded from here

fallthrough

Switch statements in Swift do not fall through the bottom of each case and into the next one. Instead, the entire switch statement completes its execution as soon as the first matching case is completed. By contrast, C requires you to insert an explicit break statement at the end of every switch case to prevent fallthrough. Avoiding default fallthrough means that Swift switch statements are much more concise and predictable than their counterparts in C, and thus they avoid executing multiple switch cases by mistake.

If you need c-Style fallthrough behaviour, it can be achieved by writing the keyword fallthrough in case you want that control is to fall to next case. For example have look into the screenshot below.

.Screen Shot 2016-02-24 at 7.17.17 AM

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *