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 anif
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
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