×


Swift Switch Statement


What is Switch Statement ?

The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch- case-default, since these three keywords go together to make up the control statement.

Note*: Switch Case works different in Swift compared to any other languages :).

Generic Syntax of switch-case Statements :-

switch expression
 {
   case expression1  :
      statement(s)
      fallthrough     /* optional */
   case expression2  :
      statement(s)
      fallthrough     /* optional */
  
   default : /* Optional */
      statement(s);
}

fallthrough is used to continue the execution of next cases in switch statements . If you do not write fallthrough then control will be out of switch block.

switch statements can accepts 'integer constants' or 'Character variables'.

What happens during the execution of switch statements ?

Firstly , expresssion under switch keyword inside paranthesis is evaluated .Then each case is evaluated one by one unless and until match is found. If no match is found , default case is being executed.

Example (Program without fallthrough statement)

/* Copyright @codzify 2017 */
import UIKit

var a = 10

switch a {
case 15  :
    print( "Value of index is 15")

case 10  :
    print( "Value of index is  10 ")
   
case 5  :
    print( "Value of index is 5")
   
default :
    print( "default case")
}

Output

Value of index is  10 

Example (Program with fallthrough statement)

/* Copyright @codzify 2017 */
import UIKit

var a = 10

switch a {
case 15  :
    print( "Value of index is 15")
   fallthrough
case 10  :
    print( "Value of index is  10 ")
   fallthrough
case 5  :
    print( "Value of index is 5")
   fallthrough
default :
    print( "default case")
}

Output

Value of index is  10 
Value of index is 5
default case

Example (Program without break statement)

/* Copyright @codzify 2017 */
import UIKit

var i = 2 ;
switch ( i ) 
{
case 1 :
    print ( "I am in case 1 \n" ) ;
   
case 2 :
    print ( "I am in case 2 \n" ) ;
  
case 3 :
    print ( "I am in case 3 \n" ) ;
  
default :
    print ( "I am in default \n" ) ;
  
}

Output

I am in case 2

Example (Program with break statement)

/* Copyright @codzify 2017 */
import UIKit

var i = 2 ;
switch ( i ) 
{
case 1 :
    print ( "I am in case 1 \n" ) ;
    break;
case 2 :
    print ( "I am in case 2 \n" ) ;
    break;
case 3 :
    print ( "I am in case 3 \n" ) ;
    break;
default :
    print ( "I am in default \n" ) ;
    break;
}

Output

I am in case 2

Switch Statements in case of string variables

/* Copyright @codzify 2017 */
import UIKit

var ch:String = "A"

switch ( ch )
{
case "A" :
    print ( "A" ) ;
    fallthrough
case "B" :
    print ( "B" ) ;
   
default :
    print ( "Print Defualt Statements" ) ; }

Output :-

A
B