Introduction
Every Programming language has control statements which decide which block of statements will execute when certain condition is matched. If you have some programming experience, then you must have heard about IF-ELSE clause.
Yes, in this article, we will talk about If-else and then Switch.
Agenda
IF Else
So, it is one of the most used programming features in any programming language. Somewhere all of us think this way.
Case
If I woke up at 8AM, then I will prepare breakfast, else I will have cornflakes. Here, we are preparing ourselves for what will we do when a condition is satisfied.
Few things which put Swift apart:
- There is no need of braces while putting a condition. Usually, we write out the if statement like this,
if(iWokeUpEarly == true) or if(iWokeUpEarly)
But, in Swift, we can omit the braces around your condition.
- Whether you have one line of code or two, you have to put those curly braces after condition. Apple thinks it enhances the readability of code.
Switch
Now, when we have number of conditions we have to match all or some of the conditions. If you are those who check every condition with if-else, then it’s an inappropriate way to do that.
Case
You will make decision according to your rank. Every rank has some different message.
And, if you use If-Else ladder, then it would be like:
Next, we’ll discuss about fall-through.
Suppose, you want same message for some specified numbers (or, cases).In C Like language, we write our code something like this.
- <code>
- Switch myRank{
- Case 1:
- Case 2:
- Case 3:
- print(“You’re RANKER”)
- Break
- .
- .
- .
- Default:
- print(“Others”)
- </code>
But, in Swift, we have Range Operators to do this.
So, you’ll ask what is Range Operators? Basically, Range Operators set the range. Say, I want to define a range of 1 to 10. Then, I will write like this:
1...10
First letter decides the lower limit and the second one decides the upper limit. Reminder: you have to put three dots (...) in between of the lower and upper bounds of the limit.
Before moving to next topic, I must tell you that we have two types of Range Operators. - Inclusive Range Operator(...)
- Exclusive Range Operator(..<)
First, Inclusive Range Operator where we are including the upper limit. Say, 1...3 which is equivalent to 1 or 2 or 3.
But, when we say 1..<3 which is equivalent to only 1 and 2, not 3. In this Exclusive Range operator, we are ignoring the upper bound limit.
Here, output is
Others because we have exclusive range operator which excludes 3. So, it goes to default case.
Series