Swift switch Statement

In this article, you will learn to use switch control statements to control the flow of your program's execution.

The switch statement is also a variety of Swift control statement e.g.if-else, guard etc., that performs different actions based on different conditions.

The beauty of switch statement is, it can compare a value with several possible matching patterns. Therefore, it can be used as a substitute for long if..else..if ladders while matching complex pattern.


Syntax of switch statement

The syntax of switch statement is:

switch variable/expression {
case value1:
	// statements
case value2:
	// statements
default:
	// statements
}

How Switch Statement in Swift works?

  • The switch expression is evaluated once.
  • It takes the expression and compares with each case value in the order (Top -> Bottom).
  • If there is a match, the statement inside the case are executed and the entire switch statement finishes its execution as soon as the first matching switch case is completed.
  • If there is no match for the case, it falls to the next case.
  • The default keyword specifies the code to run if there is no case match.

Swift switch statement flowchart

Note:The body of each case must contain at least one executable statement.


Example 1: Simple program using Switch Statement

let dayOfWeek = 4

switch dayOfWeek {
	case 1:
		print("Sunday")
	    
	case 2:
		print("Monday")
	    
	case 3:
		print("Tuesday")
	    
	case 4:
		print("Wednesday")
	    
	case 5:
		print("Thursday")
	    
	case 6:
		print("Friday")
	    
	case 7:
		print("Saturday")
	    
	default:
		print("Invalid day")
}

When you run the above program, the output will be:

Wednesday

In the above program, the switch statement starts by matching dayOfWeek value with case 1. Since dayOfWeek value doesn't match the first case value 1, it falls to the next case until one matches.

Since case 4 matches the switch expression, the statementprint("Wednesday") inside the case executes and switch case terminates. If none case was matched, statement inside default executes.


Example 2: Switch Statement with fallthrough

If you use the fallthrough keyword inside the case statement, the control proceeds to the next case even if the case value does not match with the switch expression.

let dayOfWeek = 4
switch dayOfWeek {
	case 1 :
		print("Sunday")
	    
	case 2:
		print("Monday")
	    
	case 3:
		print("Tuesday")
	    
	case 4:
		print("Wednesday")
		fallthrough
	    
	case 5:
		print("Thursday")
	    
	case 6:
		print("Friday")
	    
	case 7:
		print("Saturday")
	    
	default:
		print("Invalid day")
}

When you run the above program, the output will be:

Wednesday
Thursday

In the above program, case 4 executes the statement print("Wednesday") and fallthrough keyword proceeds to case5. The statement print("Thursday") inside case 5 executes even if the case doesn't match with the switch expression. Therefore, you can see output Thursdayin the console.


Example 3: Switch Statement with more complex patterns

let programmingLanguage = (name: "Go", version: 10)
switch programmingLanguage {

	case (let name,let version) where (version < 0 && name.count < 0) :
		print("Invalid input")

	case ("Swift",let version) where version == 4:
		print("Found latest version of Swift")

	case ("Swift" , ..<4 ):
		print("Found older version of swift)")

	case ("Swift" ,4...) :
		print("Swift version greater than 4 is not released yet")

	case ("Taylor Swift",30) :
		print("OMG. This is Taylor swift")

	case (let name, let version):  
		print("""
			Programming Language:\(name)
			Version: \(version)
			Status: Not found
		""")
}

When you run the above program, the output will be:

Programming Language:Go
Version: 10
Status: Not found

In the above program, we are matching expression programmingLanguage of type tuplewith different cases as below:

  • case (let name,let version) where (version < 0 && name.count < 0)

    This case binds the switch expression value to temporary constants or variables for use in the body of the case with let keyword. This is known as value binding.

    You can also apply condition to those values with where clause. For multiple where conditions, you can concatenate them using && operator as in the example above.

    If the case doesn't satisfy the condition defined inside where clause, statements inside those case block doesn't executes and falls through to compare next switch case.
     
  • case ("Swift" , ..<4 )

    This case matches the tuple first element with the string literal "Swift"and also checks if the second element lies inside the one sided range..<4.
     
  • case ("Swift" ,4...)

    This case matches the tuple first element with the string literal "Swift" and also checks if the second element lies inside the one sided range4….
     
  • case (let name, let version)

    This case binds every values of the tuples to the temporary constants or variables.