What is a control structure?
Control structures are used to execute blocks of code when a condition is met. To explore this we will use some of the conditional operators we covered in the previous articles.
if
if
is the most basic control structure statement checks that a condition is true
, and only in that case, will it execute the block of code written between the curly braces { }
.
var age = 18
if age >= 18 {
print("You are an adult")
}
// The console shows: "You are an adult"
else
This statement will always go immediately after an if
. The code we write between its curly braces { }
will be executed when the condition of the corresponding if
is not true
.
var age = 17
if age >= 18 {
print("You are an adult")
}
else {
print("You are a minor")
}
// The console shows: "You are a minor"
else if
There is also the possibility of including more conditions that will be checked when the condition of each previous if
is not met. The number of additional conditions you can include is unlimited.
Itβs important to understand that only one of the blocks will be executed.
var age = 15
if age < 18 { // Ages between 0 and 17
print("You are a minor")
}
else if age < 65 { // Ages between 18 and 64
print("You are an adult")
}
else { // Ages 65 and above
print("You belong to the elderly group")
}
// The console shows: "You are a minor"
Keep in mind that if we put multiple if
statements without linking them with an else
, then they will be independent and their blocks may be executed, which could give us an undesired result as in the following example.
var age = 15
if age < 18 { // Ages between 0 and 17
print("You are a minor")
}
if age < 65 { // Ages between 0 and 64: BE CAREFUL!!
print("You are an adult")
}
else { // Ages 65 and above
print("You belong to the elderly group")
}
// The console shows: "You are a minor"
// The console shows: "You are an adult"
Conditional operators
You can add more than one condition using the conditional operators we've seen in previous articles.
var age = 15
if age < 18 || age >= 65 { // Ages between 0-17 AND 65+
print("You are not an adult")
}
else { // Ages between 18 and 64
print("You are an adult")
}
var age = 15
if age >= 18 && age < 65 { // Ages between 18 and 64
print("You are an adult")
}
else { // Ages between 0-17 AND 65+
print("You are not an adult")
}
&&
operator is to separate conditions with commas.
var age = 15
if age >= 18, age < 65 { // Ages between 18 and 64
print("You are an adult")
}
else { // Ages between 0-17 AND 65+
print("You are not an adult")
}
Be the first to comment