In Swift, a switch statement is a type of control mechanism that permits a program to change its flow of control and take some decisions on the basis of some conditions imposed on the value of a variable. The control flow of a program comes out of the switch statement block as soon as the matching condition is met. It also provides a default condition if none of the mentioned conditions are met. Default statement inside a switch statement is optional provided that switch statement is exhaustive. In simple words, we can skip the default statement only if the switch statement already covers all possible cases to handle the value of the variable. If the switch statement doesn’t cover all possible cases and at the same time the default statement is skipped, then the Swift compiler throws a compile-time error. Using switch statements in a program is a good practice and should be used whenever required.
Syntax:
var myVariable = value
switch myVariable {
case condition 1:
expression 1
fallthrough // Optional
case condition 2:
expression 2
fallthrough // Optional
……………………
……………………
……………………
default: // Optional if switch block is exhaustive
expression
}
Flow chart:
Why switch statements?
Switch statements are equivalent to a bunch of if-else statements. In simple words, We can achieve the same task with the help of a bunch of if-else statements as done by the switch statement. But switch statements are more efficient as compared to if-else statements as they improve the readability of the code.
For example,
Let us consider a scenario where we want to print a string according to a marked string corresponding to a character,
- “A” -> “Apple”
- “B” -> “Boy”
- “C” -> “Cat”
- “D” -> “Dog”
We can accomplish this task with the help of a switch statement as shown below:
Swift
var myCharacter = "B"
switch myCharacter
{
case "A" :
print ( "Apple" )
case "B" :
print ( "Boy" )
case "C" :
print ( "Cat" )
case "D" :
print ( "Dog" )
default :
print ( "Invalid" )
}
|
Output:
Boy
Fallthrough Statement
A fallthrough statement allows the flow of control of a program to pass down to the next case. The body of the next case will be executed no matter whether it matches the value of the variable. Now if the next case also contains a fallthrough statement, the flow of control of the program passes down to next of the next case and so on. Otherwise, if it doesn’t contain a fallthrough statement, the flow of control of the program comes out of the switch statement immediately.
Syntax:
var myVariable = value
switch myVariable
{
case condition 1:
expression 1
fallthrough
case condition 2:
expression 2
}
Example:
Swift
var myCharacter = "B"
switch myCharacter
{
case "A" :
print ( "Apple" )
case "B" :
print ( "Boy" )
fallthrough
case "C" :
print ( "Cat" )
case "D" :
print ( "Dog" )
default :
print ( "Invalid" )
}
|
Output:
Boy
Cat
Explanation: As myCharacter is equal to “B” so the body of the second case got executed. Since, we have used the fallthrough statement just after the body of the second case, so the body of the third case will be executed also. Note that although it doesn’t satisfy the third condition (clearly, “B” is equal to “C”), the third case is getting executed. This shows that how powerful are fallthrough statements in Swift.
No implicit fallthrough
In a switch statement, if a case condition doesn’t contain a body, the Swift compiler produces a compile-time error. This is because Swift doesn’t provide an implicit fallthrough statement to deal with such case conditions.
Example:
Swift
var myCharacter = "B"
switch myCharacter
{
case "A" :
print ( "Apple" )
case "B" :
case "C" :
print ( "Cat" )
case "D" :
print ( "Dog" )
default :
print ( "Invalid" )
}
|
Output:
main.swift:18:5: error: 'case' label in a 'switch' should have at least one executable statement
case "B":
^~~~~~~~~
break
Explanation: In the above program, myCharacter is equal to “B”. Although, we have a case condition to handle this case, it doesn’t contain any executable statement in the body.
Interval matching
Swift provides a functionality using which we can use interval matching as a case condition in a switch statement.
Syntax:
case myValue1..<myValue2:
// body of case
If the value of the variable expression lies between myValue1 and myValue2 inclusive then the body of the above case would be executed.
Example:
Swift
var myInteger = 18
switch myInteger
{
case 2:
print ( "Equal to 2" )
case 3..<5:
print ( "Between 3 and 5" )
case 6..<10:
print ( "Between 6 and 10" )
case 11..<22:
print ( "Between 11 and 22" )
default :
print ( "Invalid" )
}
|
Output:
Between 11 and 22
Tuple matching
In Swift, a tuple is used to hold or group a number of elements together. The elements in a tuple can be of the same type as well as the different types. We can initialize a tuple in Swift by using the following syntax.
Syntax:
var myTuple = (myElement1, myElement2, . . . .)
Swift provides us a functionality using which we can use a tuple as a variable expression as well as a case condition in a switch statement to test multiple values. Every item of the tuple is checked against a different value. Or we can use underscore character (_) to match the possible value. Here the underscore character is known as the wildcard pattern.
case (value1, value2,. . . .):
// Body of case
case(_, value1):
// Body of case
Example:
Swift
var myTuple = (4, 10)
switch myTuple
{
case (2, 3):
print ( "First case gets executed" )
case (1...3, 5...11):
print ( "Second case gets executed" )
case (1...5, 8...13):
print ( "Third case gets executed" )
case (11...13, 15...18):
print ( "Fourth case gets executed" )
default :
print ( "Invalid" )
}
|
Output:
Third case gets executed
Value Binding
Swift allows us to initialize a temporary variable in a case condition in switch statements, this variable is only accessible in the body of the case in which it is initialized. This property is known as value binding.
Syntax
case (let myElement1, let myElement2,..., let myElementN value1, value2, ...., valueN):
// body
Now if all the constant values of the case condition are matched with the values of the variable expression then the rest of the values are automatically assigned to the corresponding temporary variables and the body of the case will be executed.
Example:
Swift
var myTuple = (2, 4, 6)
switch myTuple
{
case ( let myElement1, 3, 6):
print ( "myElement1 is equal to \(myElement1)" )
case ( let myElement1, let myElement2, 6):
print ( "myElement1 is equal to \(myElement1)" ,
"myElement3 is equal to \(myElement2)" )
case ( let myElement1, let myElement2, let myElement3):
print ( "myElement1 is equal to \(myElement1)" ,
"myElement1 is equal to \(myElement2)" ,
"myElement1 is equal to \(myElement3)" )
}
|
Output:
myElement1 is equal to 2 myElement3 is equal to 4
Explanation: In the above program, as myTuple is equal to (2, 4, 6). For the first case condition, as the second value of the tuple is not equal to the second value of myTuple, so the body of this case doesn’t get executed. For the second case condition, as the third element of the tuple is equal to the third value of myTuple, so the values of the first and second element automatically bind with the first and second elements of the case condition.
Using where clause with a switch statement
Swift also accepts where clause in case condition in a switch statement using which we can execute statements. or we can say that where clause is used to check for extra or additional conditions.
Syntax:
case let(myElement1, myElement2) where "condition":
// body
Example:
Swift
var myTuple = (20, 10)
switch myTuple
{
case let (myElement1, myElement2) where myElement1 == 3 * myElement2:
print ( "myElement1 is thrice of myElement2" )
case let (myElement1, myElement2) where myElement1 == 2 * myElement2:
print ( "myElement1 is twice of myElement2" )
case let (myElement1, myElement2) where myElement1 == myElement2:
print ( "myElement1 is equal to myElement2" )
default :
print ( "Invalid" )
}
|
Output:
myElement1 is twice of myElement2
Using compound cases with a switch statement
In Swift, we are allowed to use compound cases with a switch statement. The case conditions that share a common body can be clubbed together using commas (,). Or we can say when multiple cases separated by comma have the same body then the cases are known as compound cases. In compound cases, if any pattern matches the switch condition then that case is considered to be a match. This technique should be followed whenever required as it reduces the code size and improves the quality of our code.
Syntax:
case condition1, condition2, ....:
// body
Example:
Swift
var myCharacter = "B"
switch myCharacter
{
case "A" , "B" :
print ( "Either Apple or Boy" )
case "C" :
print ( "Cat" )
case "D" :
print ( "Dog" )
default :
print ( "Invalid" )
}
|
Output:
Either Apple or Boy
Last Updated :
24 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...