A tool most commonly used together with an if statement is the else statement.

An else statement is used to execute a block of code when the condition of an if statement is false. Think of the else to be synonymous with the word, otherwise. Do this if a condition is true, otherwise, do something else:

if condition {
   this code will run if condition is true
} else {
   this code will run if condition is false 

Two rules to remember:

  • An else statement must be used in conjunction with an if statement and cannot stand on its own.
  • An else statement does not accept a condition and is immediately followed by a code block.

In the previous exercise, we created an if statement that prints a friendly message to logged in users. Let’s use an else statement to complete this logic and print a message to users who are not logged in:

var isLoggedIn = false if isLoggedIn { print("Welcome back!") } else { print("Access Denied.") } // Prints: Access Denied.

Since the value of isLoggedIn is false, our condition is therefore, false, and the code block following the else will execute.



In Glasses.swift, we’ll create an if/else that prints an emoji representing you!

First, declare a variable, wearGlasses. Assign it a Boolean value true or false depending on if you wear glasses.


Below wearGlasses, create an if/else statement that:

  • prints, “I wear glasses” if true
  • prints, “I don’t wear glasses” otherwise

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?