The if
statement is the most basic and fundamental type of conditional in Swift. It is used to execute some code when a given condition is true
.
The structure of an if
statement is:
if condition {
this code will run if condition is true
}
- The
if
keyword is followed by a condition whose value must betrue
orfalse
. - The condition is immediately followed by a code block.
- A code block is a snippet of code enclosed in a pair of curly braces,
{
}
. - The code block is executed only when the condition is
true
. - If the condition is
false
, the code block does not run.
Suppose we’re creating an app that includes an authentication process. We’d declare the variable, isLoggedIn
to be true
and set up the following if
statement that prints a message to users who are logged in:
var isLoggedIn = true if isLoggedIn { print("Welcome back!") }
Since the value of the condition is true
, the message, Welcome back!
will get printed. If isLoggedIn
was false
, thus our condition false
, the code block wouldn’t execute and nothing would get printed.
Instructions
In LearnToCode.swift, we’ll create an if
statement that prints a message for you.
First, declare a variable, learningToCode
, using the var
keyword. Assign it a boolean value, true
.
On the following line, set up an if
statement that accepts learningToCode
as its condition.
Within the if
statement, print the message, "Don't forget to take breaks! You got this"
.
Reassign the value of learningToCode
to false
after the initial variable declaration but before the if
statement.
Observe what happens when you run the program. Did the message get printed?