Branching with the switch Statement - Images: Japanese
Hey there, everyone! Hope you're doing well.
Next up, let's take a look at something called the 'switch statement'.
A switch statement is used for branching logic, similar to an if statement. While an if statement typically handles two branches at a time, a switch statement lets you handle many different branches all at once.
Let's start with the basic syntax. It looks like this.
let n = 1
switch n {
case 1:
print("It's 1.")
case 2:
print("It's 2.")
default:
print("It's the default.")
}
The syntax has a few moving parts, so let's walk through it one piece at a time.
First, the constant n has the value 1 assigned to it. That's just a regular constant.
Next, you see the keyword 'switch'. This plays the same role as 'if' in an if statement — since we're writing a switch statement, we use 'switch'.
After that, you add a space and write the 'condition expression'. This is where you put the constant, variable, or expression you want to evaluate. In this case, that's the constant 'n'.
By the way, the condition expression part is sometimes called a conditional, a comparison target, or just an expression. On this site we use condition expression, but feel free to use whatever term you prefer.
Then you write {}, and inside you write case, followed by a space, then 1, and finally :.
This is saying: "If the value of 'n' from the condition expression equals '1', run the code after the ':'." In the example above, that means 'print("It\'s 1.")' gets executed.
The block introduced by case like this is called a 'case clause'. Pretty self-explanatory, but worth remembering.
The case 2 that follows works the same way — it means: "If n equals 2, run the code after the :."
The default at the end runs when none of the preceding case conditions matched.
Let's try it like this.
let n = 3
switch n {
case 1:
print("It's 1.")
case 2:
print("It's 2.")
default: // This is what runs.
print("It's the default.")
}
We changed the value of n to 3. None of the case values match 3.
So in this case, the default block — print("It's the default.") — is what gets executed.
The block introduced by default is called the 'default clause'. Make sure to remember it alongside the case clause from before.
Here's a quick pseudocode version in plain English — refer back to this if things get confusing.
switch conditionExpression {
case someValue: // You can have as many case clauses as you need.
// code here...
default:
// code here...
}
Now let's take a moment to look at how a switch statement flows — the order in which things are evaluated.
In a switch statement, the condition expression is evaluated first. Then the result is checked against each case clause, going from top to bottom.
Take a look at this.
switch 1 + 1 {
case 2:
print("It's 2.")
default:
print("It's the default.")
}
The condition expression here is '1 + 1'. Since the expression is evaluated first, the result '2' becomes the comparison target.
Then each case clause is checked against that result, from top to bottom. Because evaluation goes top to bottom, even if you write 'case 2' multiple times, only the first one will run.
switch 1 + 1 {
case 2: // Only this one runs.
print("It's 2.")
case 2:
print("It's 2. (second)")
case 2:
print("It's 2. (third)")
default:
print("It's the default.")
}
Still following along okay?
Now let's go over some things to watch out for with switch statements in Swift.
First, you generally need to include a default clause. So the following code is an error.
let n = 1
switch n { // Error — no default clause.
case 1:
print("It's 1.")
case 2:
print("It's 2.")
}
The "error if there's no default clause" behavior has one nuance: the default clause can be omitted only when all possible results of the condition expression are covered by case clauses. So the following is fine.
switch 1 { // This is fine.
case 1:
print("It's 1.")
}
The condition expression here is the literal value '1', so the comparison target will always be '1' and nothing else. That's why, in this case, having just 'case 1' is enough — no default clause needed, no error.
That said, when writing real programs, it's often impossible to cover every possible result of a condition expression. So it's a good habit to always include a default clause.
Also, the 'default clause' must always come last in the switch statement.
let n = 1
switch n { // Error — default clause comes first.
default:
print("It's the default.")
case 1:
print("It's 1.")
}
By the way, writing only a default clause with no case clauses is valid.
let n = 1
switch n { // Fine — only a default clause.
default:
print("It's the default.")
}
You'd rarely ever use a switch statement with only a default clause, but it's worth knowing.
Another thing to watch out for: you can't leave a case clause or default clause body empty. Like this.
let n = 1
switch n {
case 1: // Leaving case 1 with no code inside causes an error.
case 2:
print("It's 2.")
default:
print("It's the default.")
}
That said, when you're programming, there are times when a certain situation comes up and you just want to say "I don't want to do anything — just leave me alone."
For those moments, use the 'break statement'. Here's how it works.
let n = 1
switch n {
case 1:
break // Writing 'break' like this exits the switch statement — so "do nothing" is totally achievable.
case 2:
print("It's 2.")
default:
print("It's the default.")
}
Look at the 'case 1' block above. You'll see 'break' in there.
'break' is an instruction that says "exit the switch statement or loop!" So writing 'break' lets you exit the switch statement without executing any code.
In switch statements in languages other than Swift, a common behavior is: "if you don't write a break statement, execution falls through to the next case and keeps going." If you've worked with other languages, this will feel familiar.
Let's take a quick look at a PHP switch statement. The syntax is similar to Swift so you should be able to follow along.
$num = 1;
switch($num){
case 1:
var_dump('It\'s 1!');
case 2:
var_dump('It\'s 2!');
case 3:
var_dump('It\'s 3!');
default:
var_dump('It\'s the default!');
break;
}
You might expect only 'var_dump(\'It\'s 1!\');' to run since 'case 1' matches. But here's the actual output.
string(10) "It's 1!" string(10) "It's 2!" string(10) "It's 3!" string(16) "It's the default!"
Everything from 'case 1:' onward gets executed. That's the typical behavior of switch statements in other languages.
To make only the matching case execute, you need to add a 'break statement' at the end of each case clause. Like this.
$num = 1;
switch($num){
case 1: // With 'break' here, only this case 1 block runs.
var_dump('It\'s 1!');
break;
case 2:
var_dump('It\'s 2!');
break;
case 3:
var_dump('It\'s 3!');
break;
default:
var_dump('It\'s the default!');
break;
}
In Swift, execution doesn't fall through to subsequent cases automatically, so you don't need a 'break' at the end of each case clause.
On the other hand, if you do want execution to fall through to the next case, write 'fallthrough'. Here's how it works.
let n = 1
switch n {
case 1:
print("It's 1.")
fallthrough
case 2:
print("It's 2.")
default:
print("It's the default.")
}
'case 1' matches here. And since 'fallthrough' is written in the 'case 1' block, the output is as follows.
It's 1. It's 2.
The 'case 2' block also ran.
One important thing to note here. You might be thinking "so 'fallthrough' makes everything after it run" — but that's not quite right.
When you write fallthrough, it causes only the very next case clause or default clause to run unconditionally. Keep that in mind.
So if you want to replicate the "run all subsequent cases" behavior from other languages, you need to write 'fallthrough' in every case clause. Like this.
let n = 1
switch n {
case 1:
print("It's 1.")
fallthrough
case 2:
print("It's 2.")
fallthrough
case 3:
print("It's 3.")
fallthrough
default:
print("It's the default.")
}
The output of the above is as follows.
It's 1. It's 2. It's 3. It's the default.
Everything from 'case 1' onward ran. 'fallthrough' is easy to misunderstand, so be careful with it.
Alright, let's look at one more thing to watch out for with switch statements. Take a look at the following code.
let n : Int = 1
switch n {
case 1:
print("It's 1.")
case 2:
print("It's 2.")
default:
print("It's the default.")
}
Pay attention to the constant 'n'. It's typed as Int, so it can't hold a string.
That means the following code is an error.
let n : Int = 1
switch n {
case "1": // Error here.
print("It's 1.")
case 2:
print("It's 2.")
default:
print("It's the default.")
}
Focus on 'case "1"'. Since the constant 'n' in the condition expression is defined as Int, it can never hold a string.
So if you try to compare against a value of a different type in a case clause — like 'case "1"' — Swift will throw an error right there.
In other languages, the mismatched case clause would just never execute, without causing an error. Swift's switch statement is a bit stricter, so watch out for this.
In most languages other than Swift, it's standard practice to wrap the condition expression in parentheses '()'. If you've been programming for a while, the '()' style might feel more natural.
// This is PHP.
$num = 1;
switch($num){
case 1: // With 'break', only this case 1 block runs.
var_dump('It\'s 1!');
break;
case 2:
var_dump('It\'s 2!');
break;
case 3:
var_dump('It\'s 3!');
break;
default:
var_dump('It\'s the default!');
break;
}
This '()' style also works in Swift, so feel free to use it if you prefer. That said, in Swift, most people omit the parentheses. (Based on the author's observations.)
And that wraps up the switch statement! In the next article, we'll cover range operators and for-in loops. See you there!
This article was written by Sakurama.
Author's beloved small mammal |
桜舞 春人 Sakurama HarutoA Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him. |
If you find any errors or copyright issues, please contact us.