Swift programming for Beginners – Swift switch Statement

(Swift for Beginners)

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.

 

Swift programming for Beginners – Swift switch Statement

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!