Skip to Content
Learn
Conditionals
Else Statement

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.

Instructions

1.

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.

2.

Below wearGlasses, create an if/else statement that:

  • prints the emoji, ๐Ÿค“ if wearGlasses is true
  • prints the emoji, ๐Ÿ˜Š otherwise
Folder Icon

Take this course for free

Already have an account?