In swift, switch case statement is used to define multiple conditions and execute the code block of matching pattern expression.
The switch case statement is the best alternative to if-else or if else-if else statements to define multiple condition checks in swift programming language and the switch case statement will perform case-sensitive pattern matching to execute required condition statements.
Now we will see the functionality of switch-case statements in a swift programming language using an algorithm diagram.
Following is the swift switch case statement flow diagram to represent how the functionality of a switch case statement will work in a swift programming language.
If you observe above swift switch case statement flow diagram first it will check for first case statement for pattern matching in case if it TRUE then it will execute the code block within that case statement and reach end of the statement otherwise it will go to another case statement and check for the pattern matching likewise it will check all the case statements in switch till it found matching criteria.
In case if all defined case statements failed to match pattern value then the default case statements will execute and reach the end of the statement.
Following is the syntax of the switch case statement in swift programming language.
switch expression {
case pattern 1:
statements
case pattern 2:
statements
case pattern 3, pattern 4:
statements
default:
statements
}
If you observe above swift switch case statement syntax we defined multiple cases in switch statements to check for pattern matching to execute respective statements based on our pattern value.
Now we will see how to use switch case statement in a swift programming language with examples.
Following is the simple example using switch case statement in swift to check for case pattern matching before executing the expressions within the cases.
var num = 20
switch num {
case 10:
print("Given value is 10")
case 20:
print("Given value is 20")
case 30:
print("Given value is 30")
default:
print("No Matching")
}
Following is the result of above swift switch case statement example returned by playground.
Now we will see how to use swift switch-case statements with multiple conditions. Following is the example of using a swift switch case statement with multiple conditions.
let Timing = 19
let time: String
switch Timing {
case 0, 1, 2, 3, 4, 5:
time = "Early morning"
case 6, 7, 8, 9, 10, 11:
time = "Morning"
case 12, 13, 14, 15, 16:
time = "Afternoon"
case 17, 18, 19:
time = "Evening"
case 20, 21, 22, 23:
time = "Late evening"
default:
time = "INVALID Time!"
}
print(time)
Following is the result of above swift switch case statement example returned by playground.
This is how we can use swift switch case statements to define multiple condition checks based on our requirements.