Swift Tutorial Part 3: Flow Control
Welcome to part 3 of our Swift tutorial, where you’ll learn how code decisions using Booleans and repeat tasks using loops to control the flow. By Lorenzo Boaro.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Swift Tutorial Part 3: Flow Control
35 mins
- Getting Started
- Boolean Operators
- Boolean Logic
- String Equality
- The if Statement
- Encapsulating Variables
- The Ternary Conditional Operator
- Loops
- While Loops
- Repeat-while Loops
- Breaking Out of a Loop
- Advanced Control Flow
- Ranges
- For Loops
- Continue Statement
- Switch Statements
- Advanced Switch Statements
- Partial Matching
- Where to Go From Here?
The if Statement
The first and most common way of controlling the flow of a program is through the use of an if
statement, which allows the program to do something only if a certain condition evaluates as true
. For example, consider the following:
if 2 > 1 {
print("Yes, 2 is greater than 1.")
}
This is a simple if
statement. If the condition is true
, then the statement will execute the code between the braces. If the condition evaluates to false
, then the statement won’t execute the code between the braces.
You can extend an if
statement to provide code to run in case the condition turns out to be false
. This is known as the else clause. For example:
let animal = "Fox"
if animal == "Cat" || animal == "Dog" {
print("Animal is a house pet.")
} else {
print("Animal is not a house pet.")
}
Here, if animal
equals either "Cat"
or "Dog"
, then the statement will run the first block of code. If animal
does not equal either "Cat"
or "Dog"
, then the statement will run the block inside the else
part of the if
statement, printing the following to the debug area:
But you can go even further than that with if
statements. Sometimes, you want to check one condition, then another. This is where else-if
comes into play, nesting another if
statement in the else
clause of a previous if
statement.
You can use it like so:
let hourOfDay = 12
var timeOfDay = ""
if hourOfDay < 6 {
timeOfDay = "Early morning"
} else if hourOfDay < 12 {
timeOfDay = "Morning"
} else if hourOfDay < 17 {
timeOfDay = "Afternoon"
} else if hourOfDay < 20 {
timeOfDay = "Evening"
} else if hourOfDay < 24 {
timeOfDay = "Late evening"
} else {
timeOfDay = "INVALID HOUR!"
}
print(timeOfDay)
These nested if
statements test multiple conditions one-by-one until a true
condition is found. Only the code associated with that first true
condition is executed, regardless of whether subsequent else-if
conditions are true
. In other words, the order of your conditions matters!
You can add an else
clause at the end to handle the case in which none of the conditions are true
. This else
clause is optional if you don’t need it; in this example, you do need it to ensure that timeOfDay
has a valid value by the time you print it out.
In this example, the if
statement takes a number representing an hour of the day and converts it to a string that represents the part of the day to which the hour belongs. Working with a 24-hour clock, the statements are checked one-by-one in order.
In the code above, the hourOfDay
constant is 12
. Therefore, the code will print the following:
Notice that, even though both the hourOfDay < 20
and hourOfDay < 24
conditions are also true
, the statement only executes the first block whose condition is true
; in this case, the block with the hourOfDay < 17
condition.
Encapsulating Variables
if
statements introduce a new concept scope, which is a way to encapsulate variables through the use of braces.
Imagine that you want to calculate the fee to charge your client. Here’s the deal you’ve made:
Using Swift, you can calculate your fee in this way:
var hoursWorked = 45
var price = 0
if hoursWorked > 40 {
let hoursOver40 = hoursWorked - 40
price += hoursOver40 * 50
hoursWorked -= hoursOver40
}
price += hoursWorked * 25
print(price)
This code takes the number of hours and checks if it’s over 40. If so, the code calculates the number of hours over 40 and multiplies that by $50, then adds the result to the price. The code then subtracts the number of hours over 40 from the hours worked. It multiplies the remaining hours worked by $25 and adds that to the total price.
In the example above, the result is as follows:
hoursOver40
declares a new constant that you can use inside the if
statement. But what happens if you try to use it at the end of the above code?
// ...
print(price)
print(hoursOver40)
This would result in the following error:
Use of unresolved identifier 'hoursOver40'
This error informs you that you’re only allowed to use the hoursOver40
constant within the scope in which it was created. In this case, the if
statement introduced a new scope, so when that scope is finished, you can no longer use the constant.
However, each scope can use variables and constants from its parent scope. In the example above, the scope inside of the if
statement uses the price
and hoursWorked
variables, which you created in the parent scope.
The Ternary Conditional Operator
The ternary conditional operator takes a condition and returns one of two values, depending on whether the condition was true
or false
. The syntax is as follows:
(<CONDITION>) ? <TRUE VALUE> : <FALSE VALUE>
Here's an example that tests the minimum of two variables:
let a = 5
let b = 10
let min: Int
if a < b {
min = a
} else {
min = b
}
Thanks to the ternary operator, you can rewrite your code above like so:
let a = 5
let b = 10
let min = a < b ? a : b
If the condition a < b
is true
, then the result assigned back to min
will be the value of a
; if it’s false
, the result will be the value of b
.
Loops
Loops are a way of executing code multiple times. In this section, you’ll learn about the while
loop.
While Loops
A while
loop repeats a block of code while a condition is true
.
You create a while
loop this way:
while <CONDITION> {
<LOOP CODE>
}
During every iteration, the loop checks the condition. If the condition is true
, then the loop executes and moves on to another iteration. If the condition is false
, then the loop stops. Just like if
statements, while
loops introduce a scope.
The simplest while
loop takes this form:
while true {
}
This is a while
loop that never ends because the condition is always true
. An infinite loop might not cause your program to crash, but it will very likely cause your computer to freeze.
Here’s a more useful example of a while
loop:
var sum = 1
while sum < 1000 {
sum = sum + (sum + 1)
}
This code calculates a mathematical sequence, up to the point in which the value is greater than 1000
.
The loop executes as follows:
After the ninth iteration, the sum
variable is 1023
and, therefore, the loop condition of sum < 1000
becomes false
. At this point, the loop stops.