What is the switch statement in Swift?
In Swift, the switch statement tests a variable against several values for equality. It uses cases to test multiple conditions and execute code blocks based on the true condition.
Syntax
The basic structure of the switch statement is given below:
switch expression {case val1:// Code to execute when expression matches val1case val2:// Code to execute when expression matches val2default:// Code to execute when none of the cases match}
In the code above, the switch keyword is used, followed by expression to be evaluated.
case: Inside theswitchstatement, there are different cases to check for conditions.default: It is a special type of case and is executed when none of the cases matches.
Flowchart
The following diagram illustrates the flow of control in a switch statement:
Code example 1
A switch statement can be used to match against a specific value of an expression.
let choice = 2switch choice {case 1:print("Eat")case 2:print("Sleep")case 3:print("Play games")default:print("Take a rest")}
Code explanation
Line 1: We define and declare the
choicevariable.Line 3: The
choicevariable is passed to theswitchstatement, and its value is evaluated.Line 4: If the expression value is equal to
1, the code insidecase 1will get executed.Line 6: If the expression value is equal to
2, the code insidecase 2will get executed.Line 8: If the expression value is equal to
3, the code insidecase 3will get executed.Line 11: If none of the cases match, the code inside
defaultwill get executed.
Code example 2
A switch statement can also be used to match against a range of values of an expression.
let score = 67switch score {case 0..<50:print("Failed")case 50..<70:print("Pass")case 70..<85:print("Good")default:print("Excellent")}
Code explanation
Line 4: If the expression value is greater or equal to
0and less than50, the code insidecase 0..<50will get executed.Line 6: If the expression value is greater or equal to
50and less than70, the code insidecase 50..<70will get executed.Line 8: If the expression value is greater or equal to
70and less than85, the code insidecase 70..<85will get executed.Line 10: If none of the cases match, the code inside
defaultwill get executed.
Conclusion
In conclusion, the switch statement in Swift is helpful when we have multiple conditions, and based on those conditions, we have to evaluate the code block. It can also be used to execute code blocks based on different ranges of values.
Free Resources