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, anelse if
statement accepts a condition and a code block to execute for when that condition istrue
.The
else if
statement exists only between anif
and anelse
and cannot stand on its own like theif
statement can.Any number of
else if
statements can exist between anif
and anelse
.
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
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.
Following the multi line comment, declare a variable abbreviation
and assign it one of the language abbreviations.
Create an if
/else
statement that contains 3 else if
statements checking for the different values of abbreviation
.
- The
if
andelse if
statements should check ifabbreviation
is equal to,==
, an abbreviation stored in the comment. - The
if
andelse if
statement code blocks should each contain aprint
statement with the corresponding language. For example, if the abbreviation isFR
, theString
printed should beFrench
. - Use an
else
statement after the lastelse if
statement that prints the message,Abbreviation not found
.