Introduction
In this article, we will learn how to implement the decision in Swift programming language. The decision includes the if else ternary operators and etc. we will also focus on the implementation in the given example. And also, we will run it in Xcode Editor.
What is Decision Making?
- When we write a code, we need to tell the computer what it has to do in different situations. For example, in calculator when the user presses the sum button, it shows the sum of numbers. This is called Decision Making.
The if Statement
The first and most common condition in all programming languages, is the if condition which control the flow of a program through the user permission. The if condition only works when a certain condition is true. Here is an example to clear your concept.
Code
if(2>1){
print("Yes Two is Greater")
}
else{
print("Number is less")
}
The else if Statement
In the same way, you can also make else if condition. But, in else if condition, not only one of the conditions are true but sometimes, we need to check for multiple condition to be true. A good example of this is a student's grade, as follows:
If he gets above 80 marks, then print the A+ grade, if he got 70 marks, print A grade, otherwise print the else condition.
In this example, you see that two conditions are true but remember, in your code, only one condition gives 100 percent coverage; i.e., if he is pass or fail. Here is the example:
Code
var studentmarks :Int = 70
if (studentmarks == 80){
print("Excellent")
}
else if (studentmarks == 70) {
print("Good")
}
else{
print("Fail")
}
Ternary Condition Operator
Like other languages, in Swift also, there is a ternary operator that minimizes your if statement into a single line. We use the previous example here and see how we convert it into ternary conditional operator:
"will never be executed" means that the condition is true and it prints. The compiler can’t check the else condition.
Code let result = (2>1) ? ("Yes Two is Greater") : ("Number is less") Switch Statement
Another condition, to control the flow of your code, is switch statement. In switch statement, you execute a different block or a bit (totally up to you what you want to do). Here is the example to clear your concept.
We consider the 70 marks after creating a switch statement. It checks for what case is true and prints the value at the right side.
Code
var studentmarks :Int = 70
switch (studentmarks){
case 80:
print("Excellent")
case 70:
print("Good")
default:
print("Fail")
}
Main Points - If condition is executed only when a certain condition is true.
- You can extend if else statement by else if clause.
- You can use ternary operator to simplify the if statement.
- Using switch statement, you can decide which code to run, depending upon the value of a variable or constant.