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.1
2
3Number contains 2
Number contains 1
Number contains 0
Swift program that uses fallthrough statements
1 | let size = 2 |
String Example
Output is Is cat
for the example below.
Swift program that uses switch on string
1 | let name = "cat" |
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
2Default
Number = 15, Letter = b
Swift program that uses where in switch case
1 | func test(code: (Int, Character)) { |
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 | let data = ("xyz", 200) |
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 | let value = ("monkey", 200) |
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 | let tuple = ("cat", 1, "penguin") |
Reference
This is the end of post