(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.
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 withlet
keyword. This is known as value binding.You can also apply condition to those values withwhere
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
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
Latest end-to-end Learn by Coding Projects (Jupyter Notebooks) in Python and R:
All Notebooks in One Bundle: Data Science Recipes and Examples in Python & R.
End-to-End Python Machine Learning Recipes & Examples.
End-to-End R Machine Learning Recipes & Examples.
Applied Statistics with R for Beginners and Business Professionals
Data Science and Machine Learning Projects in Python: Tabular Data Analytics
Data Science and Machine Learning Projects in R: Tabular Data Analytics
Python Machine Learning & Data Science Recipes: Learn by Coding
R Machine Learning & Data Science Recipes: Learn by Coding
Comparing Different Machine Learning Algorithms in Python for Classification (FREE)
There are 2000+ End-to-End Python & R Notebooks are available to build Professional Portfolio as a Data Scientist and/or Machine Learning Specialist. All Notebooks are only $29.95. We would like to request you to have a look at the website for FREE the end-to-end notebooks, and then decide whether you would like to purchase or not.