Swift: Else If Statements

Else If Statements in Swift:

We’ve been dealing with conditionals that can only handle one condition up until now. Our program takes one course of action if that condition is met, and another if it is not. So, we use else if statements in swift for this purpose.

The else if statement is a mechanism provided by Swift that allows us to add additional conditions to a typical if/else statement.

The structure of else-if is as follows:

if Condition1 {
  this code runs when Condition1 is true 
} else if Condition2 {
  this code runs when Condition2 is true 
} else if Condition3 {
  this code runs when Condition3 is true 
} else if Condition4 {
  this code runs when Condition4 is true 
} else {
  this code runs when all previous Conditions are false 
  • An else if statement accepts a condition and a code block to execute when that condition is true, similar to an if statement.
  • The else if statement only appears between an if and an else, thus it cannot stand alone like the if statement.
  • Between an if and an else, there can be any number of else if statements.

Assume we want to alter the grading system in a school. With the use of many else if statements, we may convert numerical grades to Alphabetic grades such as "A", "B", and "C".

var Grades = 79;
var AlphabeticGrade: String;
if Grades >= 95 {
  AlphabeticGrade = "A";
} else if Grades >= 85 {
  AlphabeticGrade = "B";
} else if Grades >= 75 {
  AlphabeticGrade = "C";
} else if Grades >= 65 {
  AlphabeticGrade = "D";
} else if Grades < 65 {
  AlphabeticGrade = "F";
} else {
  AlphabeticGrade = "N/A";
// Prints: C

As the numerical grade of a student is 79, the second else if statement is executed, and the value of AlphabeticGrade is set to C.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: