The if Statement: Conditional Execution - Images: Japanese
Hey there, everyone!
Next up, let's take a look at the 'if statement'.
An 'if statement' lets you build branching logic along the lines of "if this condition is true, then do that." It's one of the most frequently used constructs in programming, so this is a super important topic.
We'll be seeing a lot of the boolean values and comparison operators from a few articles back — if you've forgotten those, go ahead and review this article before continuing.
Alright, let's jump right in with the following example.
if true {
print("Executed. #1")
}
This is what an if statement looks like.
Let's start by going over the syntax. Here's the general structure:
if condition {
// code to run...
}
Breaking it down: you write 'if', followed by a space, then the 'condition'. After that, you put the code you want to execute inside '{}'. The 'condition' part is sometimes called a 'conditional expression', 'judgment expression', or 'condition part' — 'condition' or 'conditional expression' are probably the most common terms.
The if statement runs the code inside {} when the condition evaluates to true, and skips it when it evaluates to false.
In the example above, the 'condition' is 'true', so 'print("Executed. #1")' gets executed.
You can also follow an 'if statement' with an 'else statement'. The 'else' block runs unconditionally whenever the preceding 'if statement's condition evaluates to 'false'.
Here's what that looks like:
if false {
print("Executed. #1")
}
else {
print("Executed. #2")
}
In this case, the 'if statement's condition is 'false', so 'print("Executed. #2")' runs instead.
There's also an 'else if statement'.
if false {
print("Executed. #1")
}
else if true {
print("Executed. #2")
}
This lets you chain additional conditional branches after the initial 'if statement'.
In the example above, the first if statement evaluates to false, so execution moves to the else if statement. That condition is true, so print("Executed. #2") runs.
The difference between 'else' and 'else if' is that 'else' runs unconditionally when the preceding 'if' is false, while 'else if' adds another condition to check before deciding what to run.
You can also combine multiple else if statements and an else statement together.
if false {
print("Executed. #1")
}
else if false {
print("Executed. #2")
}
else if false {
print("Executed. #3")
}
else {
print("Executed. #4")
}
In this case, the if statement is checked first, then each else if statement in order — if all of them are false, the else block runs at the end.
Note that if you include an else statement, it must always come last.
if false {
print("Executed. #1")
}
else {
print("Executed. #2")
}
else if false { // This is an error.
print("Executed. #3")
}
The code above has an else if statement following an else statement — that's an error, so watch out for that.
Also, you can't start with an 'else if statement' — the chain always has to start with an 'if statement'. Keep that in mind too.
else if false { // This is an error.
print("Executed. #1")
}
if false {
print("Executed. #2")
}
Things are getting a bit involved, so let's compare what happens when you write multiple separate 'if statements' versus chaining them with 'else if'.
if true {
print("Executed. #1")
}
if true {
print("Executed. #2")
}
Here we have two separate 'if statements'. These are completely independent — each one is evaluated on its own.
Since both conditions are true, both print("Executed. #1") and print("Executed. #2") will run.
With 'else if', the additional branches are only evaluated when the first 'if statement' is 'false' — they're part of the same chain. With multiple separate 'if statements', each one runs entirely on its own, regardless of the others.
This is a common point of confusion, so make sure you're clear on the difference.
In all the examples so far, we've been writing 'true' or 'false' directly as the condition — which isn't very useful in practice.
Let's try putting an actual expression in the 'condition' of an 'if statement'. The example below uses a comparison operator:
if 1 < 2 {
print("Executed.")
}
Take a look at the condition: it says '1 < 2'. This evaluates to 'true', so 'print("Executed.")' runs.
In practice, you'll almost always write an expression like this in the condition of an 'if statement' — so keep that in mind.
Now let's go over some important things to watch out for with 'if statements' in Swift.
In many other languages, you can put all sorts of things in the condition — numbers, strings, arrays, associative arrays, and more.
In those languages, a value of '0' or an empty string is treated as 'false', while a non-zero number or non-empty string is treated as 'true' — there's a clear distinction between what counts as "truthy" and "falsy".
In Swift, however, if the condition doesn't evaluate to a boolean, you'll get an error. Here's what that looks like:
if true { // OK.
}
if 1 < 2 { // '1 < 2' evaluates to the boolean 'true', so this is OK.
}
if 1 { // The number '1' is not a boolean, so this is an error.
}
In other languages, what counts as "truthy" or "falsy" varies from language to language, which can be annoying to look up and is a common source of unexpected bugs.
Swift's rule of "it must be a boolean — no exceptions" is actually quite clear and straightforward. That said, if you're coming from another language, this is an easy thing to slip up on, so just keep it in mind.
In some other languages, the 'if statement' syntax requires putting the condition inside '()'. If you've been programming since the old days, that style might feel more natural. It looks like this:
if (true) { // Condition goes inside '()'.
}
This syntax works in Swift too, so you can use it if you like.
That said, the majority of Swift developers seem to write it without (). (Based on the author's observations.) It really comes down to personal preference.
In some other languages, the {} braces can be omitted from an if statement when the body is just one line. Like this:
if true print("test")
else if true print("test")
This is not valid in Swift — so watch out. In Swift, {} is required regardless of whether the body is one line or many.
And that's everything on 'if statements'. In the next article, we'll cover logical operators. 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.