Updated for Xcode 14.2
When you’re just learning Swift, it can be a bit hard to know when to use else
, when to use else if
, and what the difference really is.
Well, let’s start with an example value we can work with:
let score = 9001
(In case you were wondering, yes this does mean we’ll be relying on the Dragonball Z meme.)
We could write a simple condition to check whether the score is over 9000 like this:
if score > 9000 {
print("It's over 9000!")
}
Now, if we want to print a different message for scores equal to or under 9000, we could write this:
if score > 9000 {
print("It's over 9000!")
}
if score <= 9000 {
print("It's not over 9000!")
}
That works perfectly fine, and your code would do exactly what you expect. But now we’ve given Swift more work to do: it needs to check the value of score
twice. That’s very fast here with a simple integer, but if our data was more complex then it would be slower.
This is where else
comes in, because it means “if the condition we checked wasn’t true, run this code instead.”
So, we could rewrite our previous code to this:
if score > 9000 {
print("It's over 9000!")
} else {
print("It's not over 9000!")
}
With that change Swift will only check score
once, plus our code is shorter and easier to read too.
Now imagine we wanted three messages: one when the score is over 9000, one when exactly 9000, and one when it’s under 9000. We could write this:
if score > 9000 {
print("It's over 9000!")
} else {
if score == 9000 {
print("It's exactly 9000!")
} else {
print("It's not over 9000!")
}
}
Again, that’s exactly fine and works just like you would hope. However, we can make the code easier to read by using else if
, which lets us combine the else
with the if
directly after it, like this:
if score > 9000 {
print("It's over 9000!")
} else if score == 9000 {
print("It's exactly 9000!")
} else {
print("It's not over 9000!")
}
To try this out, I want to use a Swift function called print()
: you run it with some text, and it will be printed out.
That makes our code a little easier to read and understand, because rather than having nested conditions we have a single flow we can read down.
You can have as many else if
checks as you want, but you need exactly one if
and either zero or one else
.
SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.