Open In App

Swift – Switch Statement

Improve
Improve
Like Article
Like
Save
Share
Report

In Swift, a switch statement is a type of control mechanism that permits a program to change its flow of control and take some decisions on the basis of some conditions imposed on the value of a variable. The control flow of a program comes out of the switch statement block as soon as the matching condition is met. It also provides a default condition if none of the mentioned conditions are met. Default statement inside a switch statement is optional provided that switch statement is exhaustive. In simple words, we can skip the default statement only if the switch statement already covers all possible cases to handle the value of the variable. If the switch statement doesn’t cover all possible cases and at the same time the default statement is skipped, then the Swift compiler throws a compile-time error. Using switch statements in a program is a good practice and should be used whenever required. 

Syntax:

var myVariable = value

switch myVariable {

             case condition 1:

             expression 1

             fallthrough                   // Optional

             case condition 2:

             expression 2

             fallthrough                   // Optional

             ……………………

             ……………………

             ……………………

             default:                      // Optional if switch block is exhaustive

             expression

}

Flow chart:

Why switch statements?

Switch statements are equivalent to a bunch of if-else statements. In simple words, We can achieve the same task with the help of a bunch of if-else statements as done by the switch statement. But switch statements are more efficient as compared to if-else statements as they improve the readability of the code.

For example,

Let us consider a scenario where we want to print a string according to a marked string corresponding to a character,

  • “A” -> “Apple”
  • “B” -> “Boy”
  • “C” -> “Cat”
  • “D” -> “Dog”

We can accomplish this task with the help of a switch statement as shown below:

Swift




// Swift program to illustrate the 
// working of switch statement
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter 
{
      
    // If myCharacter is equal to "A"
    case "A":
      
        // Then print "Apple"
        print("Apple")
      
    // If myCharacter is equal to "B"
    case "B":
      
        // Then print "Apple"  
        print("Boy")
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}


Output:

Boy

Fallthrough Statement 

A fallthrough statement allows the flow of control of a program to pass down to the next case. The body of the next case will be executed no matter whether it matches the value of the variable.  Now if the next case also contains a fallthrough statement, the flow of control of the program passes down to next of the next case and so on. Otherwise, if it doesn’t contain a fallthrough statement, the flow of control of the program comes out of the switch statement immediately. 

Syntax:

var myVariable = value

switch myVariable 

{

             case condition 1:

             expression 1

             fallthrough                   

             case condition 2:

             expression 2

}

Example:

Swift




// Swift program to illustrate the working 
// of fallthrough statement in switch statement
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter
{
      
    // If myCharacter is equal to "A"
    case "A":
      
        // Then print "Apple"
        print("Apple")
      
    // If myCharacter is equal to "B"
    case "B":
      
        // Then print "Apple"  
        print("Boy")
      
    // Using fallthrough so that
    // below case also gets executed
    fallthrough
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}


Output:

Boy
Cat

Explanation: As myCharacter is equal to “B” so the body of the second case got executed. Since, we have used the fallthrough statement just after the body of the second case, so the body of the third case will be executed also. Note that although it doesn’t satisfy the third condition  (clearly, “B” is equal to “C”), the third case is getting executed. This shows that how powerful are fallthrough statements in Swift. 

No implicit fallthrough

In a switch statement, if a case condition doesn’t contain a body, the Swift compiler produces a compile-time error. This is because Swift doesn’t provide an implicit fallthrough statement to deal with such case conditions. 

Example:

Swift




// Swift program to illustrate 
// No implicit fallthrough
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter 
{
      
    // If myCharacter is equal to "A"
    case "A":
      
        // Then print "Apple"
        print("Apple")
      
    // If myCharacter is equal to "B"
    case "B":
      
    // No body
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}


Output:

main.swift:18:5: error: 'case' label in a 'switch' should have at least one executable statement
    case "B":
    ^~~~~~~~~
              break

Explanation: In the above program, myCharacter is equal to “B”. Although, we have a case condition to handle this case, it doesn’t contain any executable statement in the body. 

Interval matching

Swift provides a functionality using which we can use interval matching as a case condition in a switch statement.

Syntax:

case myValue1..<myValue2:
// body of case

If the value of the variable expression lies between myValue1 and myValue2 inclusive then the body of the above case would be executed.

Example:

Swift




// Swift program to illustrate the interval 
// matching in the switch statement
  
// Initializing an integer
var myInteger = 18
  
// Switch block 
switch myInteger 
{
      
    // If myInteger is equal to 2
    case 2:
      
        // Then print "Apple"
        print("Equal to 2")
      
    // If myInteger is between 3 and 5
    case 3..<5:
      
        // Then print "Between 3 and 5"  
        print("Between 3 and 5")
      
    // If myInteger is between 6 and 10  
    case 6..<10:
      
        // Then print "Between 6 and 10"  
        print("Between 6 and 10")
      
    // If myInteger is between 11 and 22
    case 11..<22:
      
        // Then print "Between 11 and 22"  
        print("Between 11 and 22")
      
    // Default statement
    default:
        print("Invalid")
}


Output:

Between 11 and 22

Tuple matching

In Swift, a tuple is used to hold or group a number of elements together. The elements in a tuple can be of the same type as well as the different types. We can initialize a tuple in Swift by using the following syntax.

Syntax:

var myTuple = (myElement1, myElement2, . . . .)

Swift provides us a functionality using which we can use a tuple as a variable expression as well as a case condition in a switch statement to test multiple values. Every item of the tuple is checked against a different value. Or we can use underscore character (_) to match the possible value. Here the underscore character is known as the wildcard pattern.

case (value1, value2,. . . .):
// Body of case
case(_, value1):
// Body of case

Example:

Swift




// Swift program to illustrate the working
// of tuples with switch statement
  
// Initializing a tuple
var myTuple = (4, 10)
  
// Switch block 
switch myTuple 
{
  
    // If myTuple is equal to (2,3)
    case (2, 3):
      
        // Then print
        print("First case gets executed")
      
    // If myTuple is (between 1 and 3,between 5 and 11) 
    case (1...3, 5...11):
      
        // Then print  
        print("Second case gets executed")
      
    // If myTuple is (between 1 and 5, between 8 and 13)   
    case (1...5, 8...13):
      
        // Then print  
        print("Third case gets executed")
          
    // If myTuple is (between 11 and 13, between 15 and 18) 
    case (11...13, 15...18):
      
        // Then print  
        print("Fourth case gets executed")
      
    // Default statement
    default:
        print("Invalid")
}


Output:

Third case gets executed

Value Binding

Swift allows us to initialize a temporary variable in a case condition in switch statements, this variable is only accessible in the body of the case in which it is initialized. This property is known as value binding.

Syntax

case (let myElement1, let myElement2,..., let myElementN value1, value2, ...., valueN):
     // body

Now if all the constant values of the case condition are matched with the values of the variable expression then the rest of the values are automatically assigned to the corresponding temporary variables and the body of the case will be executed.

Example:

Swift




// Swift program to illustrate the working 
// of value binding with switch statement
  
// Initializing a tuple
var myTuple = (2, 4, 6)
  
// Switch block 
switch myTuple 
{
  
    // If myTuple is equal to (2,3)
    case (let myElement1, 3, 6):
      
        // Then print
        print("myElement1 is equal to \(myElement1)")
      
    // If myTuple is (between 1 and 3, between 5 and 11) 
    case (let myElement1, let myElement2, 6):
      
        // Then print
        print("myElement1 is equal to \(myElement1)"
              "myElement3 is equal to \(myElement2)")
      
    // If myTuple is (between 1 and 5, between 8 and 13)   
    case (let myElement1, let myElement2, let myElement3):
      
        // Then print
        print("myElement1 is equal to \(myElement1)"
              "myElement1 is equal to \(myElement2)"
              "myElement1 is equal to \(myElement3)")
      
}


Output:

myElement1 is equal to 2 myElement3 is equal to 4

Explanation: In the above program, as myTuple is equal to (2, 4, 6). For the first case condition, as the second value of the tuple is not equal to the second value of myTuple, so the body of this case doesn’t get executed. For the second case condition, as the third element of the tuple is equal to the third value of myTuple, so the values of the first and second element automatically bind with the first and second elements of the case condition.

Using where clause with a switch statement

Swift also accepts where clause in case condition in a switch statement using which we can execute statements. or we can say that where clause is used to check for extra or additional conditions.

Syntax:

case let(myElement1, myElement2) where "condition":
     // body

Example:

Swift




// Swift program to illustrate the 
// working of where clause with switch statement
  
// Initializing a tuple
var myTuple = (20, 10)
  
// Switch block 
switch myTuple
{
  
    // If myElement1 is thrice of myElement2
    case let (myElement1, myElement2) where myElement1 == 3 * myElement2:
        
        // Then print
        print("myElement1 is thrice of myElement2")
      
    // If myElement1 is twice of myElement2
    case let (myElement1, myElement2) where myElement1 == 2 * myElement2:
       
        // Then print
        print("myElement1 is twice of myElement2")
      
    // If myElement1 is equal to myElement2
    case let (myElement1, myElement2) where myElement1 ==  myElement2:
      
        // Then print
        print("myElement1 is equal to myElement2")
      
    default:
      
        // Then print
        print("Invalid")
}


Output:

myElement1 is twice of myElement2

Using compound cases with a switch statement

In Swift, we are allowed to use compound cases with a switch statement. The case conditions that share a common body can be clubbed together using commas (,). Or we can say when multiple cases separated by comma have the same body then the cases are known as compound cases. In compound cases, if any pattern matches the switch condition then that case is considered to be a match. This technique should be followed whenever required as it reduces the code size and improves the quality of our code.

Syntax:

case condition1, condition2, ....:
    // body

Example:

Swift




// Swift program to illustrate the compound cases
  
// Initializing a character
var myCharacter = "B"
  
// Switch block 
switch myCharacter
{
  
    // If myCharacter is equal to either "A" or "B"
    case "A", "B":
      
        // Then print "Either Apple or Boy"
        print("Either Apple or Boy")
      
    // If myCharacter is equal to "C"  
    case "C":
      
        // Then print "Cat" 
        print("Cat")
      
    // If myCharacter is equal to "D"   
    case "D":
      
        // Then print "Dog"   
        print("Dog")
      
    // Default statement
    default:
        print("Invalid")
}


Output:

Either Apple or Boy


Last Updated : 24 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads