Using Switch statement in Swift?
Contents
What is Switch statement?
According to Swift document, a switch statement is:
A switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully. A switch statement provides an alternative to the if statement for responding to multiple potential states.
Basiclly speaking, in a switch statement, it will try all possible values for a variable. Also, a switch statement must have a default value.
All the following code are based on Swift 3.0.
A Simple Example
Output is Ten
for the example below.
Swift program that uses switch
1 | let id = 10 |
Multiple Case Values Example
Output is Medium
for the example below.
Swift program that uses multiple case values
1 | let size = 3 |
Ranges Example
Output is Upper half
for the example below.
Swift program that uses ranges in cases
1 | let code = 70 |
Fallthrough Example
Fallthrough
means that control proceeds to the next case in a switch, and the next case is entered even if the value does not match.
Output is below for the following example.
Number contains 2
Number contains 1
Number contains 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>Swift program that uses fallthrough statements
``` swift
let size = 2
// Use switch with fallthrough statements.
switch size {
case 3:
// This case will execute statements in case 2, 1 and 0.
print("Number contains 3")
fallthrough
case 2:
print("Number contains 2")
fallthrough
case 1:
print("Number contains 1")
fallthrough
case 0:
print("Number contains 0")
default:
print("Invalid")
}
### String Example
Output is `Is cat` for the example below.
>Swift program that uses switch on string
1
2
3
4
5
6
7
8
9
10
11
12
13
let name = "cat"
// Switch on the name string.
switch name {
case "bird":
print("Is bird")
case "dog":
print("Is dog")
case "cat":
print("Is cat") // This is printed.
default:
print("Something else")
}
### Where Example
Where method can do further checking in some cases. For instance, we want to print out a tuple argument with a integer greater than 10. The following code output is below.
1
2
Default
Number = 15, Letter = b
>Swift program that uses where in switch case
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func test(code: (Int, Character)) {
// Switch on the tuple argument.
// We use let to allow the tuple items to be referenced.
// We use where to test a part of the tuple.
switch code {
case let(number, letter) where number >= 10:
print("Number = \(number), Letter = \(letter)")
default:
print("Default")
}
}
// Call test with a tuple argument.
test(code: (5, "a"))
// Call test again.
test(code: (15, "b"))
### Tuple Example
We use a "tuple pattern" to match all items in the tuple.
Output is `Is xyz200` for the example below.
>Swift that uses tuple switch
1
2
3
4
5
6
7
8
let data = ("xyz", 200)
// Match complete tuple values.
switch (data) {
case ("abc", 300): print("Is abc300")
case ("xyz", 200): print("Is xyz200")
default: print("Not known")
}
### Let Values
A case block can capture values in a tuple switch. We use the "let" keyword and provide an identifier.
Output is `Monkey has size 200` for the example below.
>Swift that uses let, value switch
1
2
3
4
5
6
7
let value = ("monkey", 200)
// Use let to capture a variable in a tuple.
switch (value) {
case ("monkey", let size): print("Monkey has size \(size)")
default: break
}
### Tuples With Any Value
With an underscore, we can match just parts of a tuple in a switch.
Output is `Second value is 1` for the example below.
>Swift that switches, matches any tuple value
1
2
3
4
5
6
7
8
9
let tuple = ("cat", 1, "penguin")
// Switch on tuple.
// ... Match second value of the tuple.
switch (tuple) {
case (_, 1, _): print("Second value is 1")
case (_, 2, _): print("Second value is 2")
default: print("No case")
}
### Reference
* [Control Flow](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html)
* [Switch in Swift](https://www.dotnetperls.com/switch-swift)
---
*This is the end of post*