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.
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 the switch
statement, 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.
The following diagram illustrates the flow of control in a switch
statement:
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")}
Line 1: We define and declare the choice
variable.
Line 3: The choice
variable is passed to the switch
statement, and its value is evaluated.
Line 4: If the expression value is equal to 1
, the code inside case 1
will get executed.
Line 6: If the expression value is equal to 2
, the code inside case 2
will get executed.
Line 8: If the expression value is equal to 3
, the code inside case 3
will get executed.
Line 11: If none of the cases match, the code inside default
will get executed.
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")}
Line 4: If the expression value is greater or equal to 0
and less than 50
, the code inside case 0..<50
will get executed.
Line 6: If the expression value is greater or equal to 50
and less than 70
, the code inside case 50..<70
will get executed.
Line 8: If the expression value is greater or equal to 70
and less than 85
, the code inside case 70..<85
will get executed.
Line 10: If none of the cases match, the code inside default
will get executed.
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