Implement Decision Making In Swift Programming Language

Introduction

In this blog, we will learn how to implement a decision in Swift programming language. The decision includes the if else ternary operators etc. We will also focus on the implementation in the given example.

What is decision making?

  • It is a decision making statement and allows us to take the different paths of the statement, which depends on a condition.
  • For example, in calculator, when the user presses the sum button, it shows the sum of the numbers.
  • This is called decision making.

Decision making types

  • if statement
  • if else statement
  • nested if else statment
  • switch statement

if statement

  • The first and most common condition in all the programming languages is the if condition, which controls the flow of a program through the user permission. 
  • It is if condition, which only works when a certain condition is true.
if else statement

I have if else statement, which is dedicated to the variable of the sample program .
  1. var a = 10  
  2. var b = 20  
  3. if (a < b) {  
  4.     print("a is less than b")  
  5. else {  
  6.     print("b is greater than a")  
  7. }  
if else statement states the condition to be true
  1. print("a is less than b")  
On the contrary, else statement states the condition to be false.
  1. print("b is greater than a") exit the program.  
Nested if else statement

I have nested if else statement dedicated to the variable of the sample program.
  1. var a = 10  
  2. var b = 20  
  3. var c = 30  
  4. if (a < b) {  
  5.     print("a is less than b")  
  6. }  
  7. if (b < c) {  
  8.     print("b is less than c")  
  9. else {  
  10.     print("c is less than b")  
  11. }  
if statement states the condition to be true.
  1. print("a is less than b")
Again, if statement states the condition to be true.
  1. print("b is less than c")
It is else statement, which states the condition to be false.
  1. print("c is less than b") so exit the program.
Switch statement
  • The switch statement is a control satement.
  • This handles multiple selections by passing control to one of the case statements.
  • It is not necessary to use it in Swift programming language in break statement.
Example program
  1. var index = 10  
  2. switch index {  
  3.     case 100:  
  4.         print("value of index is 100")  
  5.     case 10, 15:  
  6.         print("value of index is 10 or 15")  
  7.     case 5:  
  8.         print("value of index is 5")  
  9.     default:  
  10.         print("default case")  
  11. }  
Output
  1. value of index is either 10 or 15
This is the basic concept of decision making in Swift programming language.
Ebook Download
View all
Learn
View all