Swift Switch Statement

The Swift switch statement is used for conditional execution of statements based on the value of an expression.

In this tutorial, we will learn about Swift switch statement, its syntax and usage with the help of examples.

Syntax

The syntax of Switch statement is.

switch expression {
    case value1 :
        statement(s)
        some more statement(s)
    case value2 :
        statement(s)

    /* some more case statements */
   
    default : /* Optional */
        statement(s)
}

where

  • expression evaluates to a value of primitive datatype.
  • value1, value2 .. are some of the possible constants for which we have corresponding code blocks. When expression evaluates to one of the value1, value2, etc., corresponding statements are executed. If no match happens, default block is executed.

We can have one or more statements for each case block.

Note: default block is optional, but in that case, switch statement has to be exhaustive. Meaning, there must be a case block for each possible value of the expression.

Example 1 – Basic Swift Switch Example

In this example, we have a simple expression with two variables. We have case blocks with values 4, 5, 6 and default. When the expression’s value matches any of the values, corresponding block is executed.

main.swift

var a=2
var b=3

switch a+b {
    case 4 :
        print("a+b is 4.")
        print("a+b is four.")
    case 5 :
        print("a+b is 5.")
        print("a+b is five.")
    case 6 :
        print("a+b is 6.")
        print("a+b is six.")
    default :
        print("no value has been matched for a+b.")
}

Output

a+b is 5.
a+b is five.

The expression evaluated to 5 and the case 5 : block has been executed.

Example 2 – Switch without default block

We know that default block is optional. In this example, we have a switch block with no default block. As we are not using default block, we should have the case blocks for each possible value of expression. So, we shall take a boolean expression.

main.swift

var a=true
var b=false

switch a&&b {
    case true :
        print("Hello User.")
    case false :
        print("Welcome User.")
}

Output

Welcome User.

The expression evaluated to false and the case false : block has been executed.

Conclusion

In this Swift Tutorial, we have learned about Switch statement in Swift programming, its syntax and usage with the help of example programs.