Previously, we learned how if-else
statements create two distinct paths for our Swift code: one for when the condition is true
, and another for when it's false
.
Engagement Message
But what if we need to check several different conditions?
Imagine checking if a number is positive, negative, or zero. An if-else
only gives us two options. We need a way to add more checks!
Engagement Message
Can you think of a sample application where this scenario of needing more checks could come up?
This is where else if
comes in! It lets you test another condition only if the preceding if
(or else if
) condition was false
.
It adds another branch to our decision-making path.
Engagement Message
To help you memorize it, can you try naming the 3 conditional statements you just learned?
You can chain multiple else if
statements after an if
. An optional at the very end catches anything that didn't match the or any conditions.
