Learn
Conditionals
Else If Statements

Until now, we’ve been working with conditionals that can handle only one condition. If that condition is met, our program follows one course of action, otherwise it follows another.

Swift provides us with a tool called the else if statement which allows us to add additional conditions to a standard if/else statement.

Here’s how it works:

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 {
  this code runs when all previous conditions are false 
}
  • Similarly to an if statement, an else if statement accepts a condition and a code block to execute for when that condition is true.

  • The else if statement exists only between an if and an else and cannot stand on its own like the if statement can.

  • Any number of else if statements can exist between an if and an else.

Working off the previous example, assume we’d like to update the grading scale in a school to use the academic grading scale used in the U.S..

We can translate numerical grades to letter grades, "A", "B", "C", etc. with the help of multiple else if statements:

let grade = 85 let letterGrade: String if grade >= 90 { letterGrade = "A" } else if grade >= 80 { letterGrade = "B" } else if grade >= 70 { letterGrade = "C" } else if grade >= 60 { letterGrade = "D" } else if grade < 60 { letterGrade = "F" } else { letterGrade = "N/A" } print(letterGrade) // Prints: B

Since a student’s numerical grade is 85, the first else if statement executes, and the value of letterGrade becomes "B".

Instructions

1.

In Languages.swift, we’ll write a program that translates the abbreviation of languages spoken in New York.

First, Google 4 languages spoken in New York and their abbreviations. Store each language name and abbreviation in a multi line comment at the top.

2.

Following the multi line comment, declare a variable abbreviation and assign it one of the language abbreviations.

3.

Create an if/else statement that contains 3 else if statements checking for the different values of abbreviation.

  • The if and else if statements should check if abbreviation is equal to, ==, an abbreviation stored in the comment.
  • The if and else if statement code blocks should each contain a print statement with the corresponding language. For example, if the abbreviation is FR, the String printed should be French.
  • Use an else statement after the last else if statement that prints the message, Abbreviation not found.
Folder Icon

Take this course for free

Already have an account?