Swift Tutorial Part 3: Flow Control

Matt Galloway

part3-feature

Welcome to the third and final part of this Swift mini-series! If you haven’t read through Part 1 or Part 2 of this series, we suggest you do that first.

When writing a computer program, you need to be able to tell the computer what to do in different scenarios. For example, a calculator app would need to do one thing if the user tapped the addition button and another thing if the user tapped the subtraction button.

In computer-programming terms, this concept is known as control flow. It is so named because the flow of the program is controlled by various methods.

In this tutorial, you’ll learn how to make decisions and repeat tasks in your programs by using syntax to control the flow. You’ll also learn about Booleans, which represent true and false values, and how you can use these to compare data.

Getting Started

You’ve seen a few types now, such as Int, Double and String. Here you’ll learn about another type, one that will let you compare values through the comparison operators.

When you perform a comparison, such as looking for the greater of two numbers, the answer is either true or false. Swift has a data type just for this! It’s called a Bool, which is short for Boolean, after a rather clever man named George Boole who invented an entire field of mathematics around the concept of true and false.

This is how you use a Boolean in Swift:

let yes: Bool = true
let no: Bool = false

And because of Swift’s type inference, you can leave off the type:

let yes = true
let no = false

A Boolean can only be either true or false, denoted by the keywords true and false. In the code above, you use the keywords to set the initial state of each constant.

Boolean Operators

Booleans are commonly used to compare values. For example, you may have two values and you want to know if they’re equal: either they are (true) or they aren’t (false).

In Swift, you do this using the equality operator, which is denoted by ==:

let doesOneEqualTwo = (1 == 2)

Swift infers that doesOneEqualTwo is a Bool. Clearly, 1 does not equal 2, and therefore doesOneEqualTwo will be false.

Similarly, you can find out if two values are not equal using the != operator:

let doesOneNotEqualTwo = (1 != 2)

This time, the comparison is true because 1 does not equal 2, so doesOneNotEqualTwo will be true.

The prefix ! operator, also called the not-operator, toggles true to false and false to true. Another way to write the above is:

let alsoTrue = !(1 == 2)

Because 1 does not equal 2, (1==2) is false, and then ! flips it to true.

Two more operators let you determine if a value is greater than (>) or less than (<) another value. You’ll likely know these from mathematics:

let isOneGreaterThanTwo = (1 > 2)
let isOneLessThanTwo = (1 < 2)

And it’s not rocket science to work out that isOneGreaterThanTwo will equal false and isOneLessThanTwo will equal true.

There’s also an operator that lets you test if a value is less than or equal to another value: <=. It’s a combination of < and ==, and will therefore return true if the first value is either less than the second value or equal to it.

Similarly, there’s an operator that lets you test if a value is greater than or equal to another — you may have guessed that it’s >=.

Boolean Logic

Each of the examples above tests just one condition. When George Boole invented the Boolean, he had much more planned for it than these humble beginnings. He invented Boolean logic, which lets you combine multiple conditions to form a result.

One way to combine conditions is by using AND. When you AND together two Booleans, the result is another Boolean. If both input Booleans are true, then the result is true. Otherwise, the result is false.

george_boole

In Swift, the operator for Boolean AND is &&, used like so:

let and = true && true

In this case, and will be true. If either of the values on the right was false, then and would be false.

Another way to combine conditions is by using OR. When you OR together two Booleans, the result is true if either of the input Booleans is true. Only if both input Booleans are false will the result be false.

In Swift, the operator for Boolean OR is ||, used like so:

let or = true || false

In this case, or will be true. If both values on the right were false, then or would be false. If both were true, then or would still be true.

In Swift, Boolean logic is usually applied to multiple conditions. Maybe you want to determine if two conditions are true; in that case, you’d use AND. If you only care about whether one of two conditions is true, then you’d use OR.

For example, consider the following code:

let andTrue = 1 < 2 && 4 > 3
let andFalse = 1 < 2 && 3 > 4

let orTrue = 1 < 2 || 3 > 4
let orFalse = 1 == 2 || 3 == 4

Each of these tests two separate conditions, combining them with either AND or OR.

It’s also possible to use Boolean logic to combine more than two comparisons. For example, you can form a complex comparison like so:

let andOr = (1 < 2 && 3 > 4) || 1 < 4

The parentheses disambiguates the expression. First Swift evaluates the sub-expression inside the parentheses, and then it evaluates the full expression, following these steps:

1. (1 < 2 && 3 > 4) || 1 < 4
2. (true && false) || true
3. false || true
4. true

String Equality

Sometimes you want to determine if two strings are equal. For example, a children’s game of naming an animal in a photo would need to determine if the player answered correctly.

In Swift, you can compare strings using the standard equality operator, ==, in exactly the same way as you compare numbers. For example:

let guess = "dog"
let dogEqualsCat = guess == "cat"

Here, dogEqualsCat is a Boolean that in this case equals false, because "dog" does not equal "cat". Simple!

Just as with numbers, you can compare not just for equality, but also to determine is one value is greater than or less that another value. For example:

let order = "cat" < "dog"

This syntax checks if one string comes before another alphabetically. In this case, order equals true because "cat" comes before "dog".

The subject of equality brings up an interesting feature of Unicode: There are two ways to represent some characters. One example is the é in café, which is an e with an acute accent. You can represent this character with either a single character or with two.

You saw the single character, code point 233, earlier in this tutorial. The two-character case is an e on its own followed by an acute accent combining character, which is a special character that modifies the previous character.

So you can represent the e with an acute accent by either of these means:

combining_characters

The combination of these two characters in the second diagram forms what is known as a grapheme cluster.

Another example of combining characters are the special characters used to change the skin color of certain emojis. For example:

emoji_skin_colour

Here, the thumbs up emoji is followed by a skin tone combining character. On platforms that support it, including iOS and macOS, the rendered emoji is a single thumbs up character with the skin tone applied.

Combining characters make equality of strings a little trickier. For example, consider the word café written once using the single é character, and once using the combining character, like so:

cafe_vs_cafe_combining

These two strings are of course logically equal. When they are printed onscreen, they look exactly the same. But they are represented inside the computer in different ways. Many programming languages would consider these strings to be unequal because those languages work by comparing the characters one by one. Swift, however, considers these strings to be equal by default. Let’s see that in action:

let stringA = "café"
let stringB = "cafe\u{0301}"

let equal = stringA == stringB
Note: In the code above, the acute accent combining character is written using the Unicode shorthand, which is \u followed by the code point in hexadecimal, in braces. You can use this shorthand to write any Unicode character. I had to use it here for the combining character because there’s no way to type this character on my keyboard!

In this case, equal is true, because the two strings are logically the same.

String comparison in Swift uses a technique known as canonicalization. Say that three times fast! Before checking equality, Swift canonicalizes both strings, which means they’re converted to use the same special character representation.

It doesn’t matter which way it does the canonicalization — using the single character or using the combining character — as long as both strings get converted to the same style. Once the canonicalization is complete, Swift can compare individual characters to check for equality.

Mini-exercises

  1. Create a constant called myAge and set it to your age. Then, create a constant called isTeenager that uses Boolean logic to determine if the age denotes someone in the age range of 13 to 19.
  2. Create another constant called theirAge and set it to my age, which is 30. Then, create a constant called bothTeenagers that uses Boolean logic to determine if both you and I are teenagers.
  3. Create a constant called reader and set it to your name as a string. Create a constant called author and set it to my name, Matt Galloway. Create a constant called authorIsReader that uses string equality to determine if reader and author are equal.
  4. Create a constant called readerBeforeAuthor which uses string comparison to determine if reader comes before author.

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 is 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 is false, then the statement won’t execute the code between the braces. It’s as simple as that!

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. Here’s an 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:

Animal is not a house pet.

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
let timeOfDay: String

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 where 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 representing 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:

  • The first check is to see if the hour is less than 6. If so, that means it’s early morning.
  • If the hour is not less than 6, the statement continues to the first else-if, where it checks the hour to see if it’s less than 12.
  • Then in turn, as conditions prove false, the statement checks the hour to see if it’s less than 17, then less than 20, then less than 24.
  • Finally, if the hour is out of range, the statement prints that information to the console.

In the code above, the hourOfDay constant is 12. Therefore, the code will print the following:

Afternoon

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.

Short Circuiting

An important fact about if statements is what happens when there are multiple Boolean conditions separated by ANDs (&&) or ORs (||).

Consider the following code:

if 1 > 2 && name == "Matt Galloway" {
  // ...
}

The first condition of the if-statement, 1 > 2 is false. Therefore the whole expression cannot ever be true. So Swift will not even bother to check the second part of the expression, namely the check of name.

Similarly, consider the following code:

if 1 < 2 || name == "Matt Galloway" {
  // ...
}

Since 1 < 2 is true, the whole expression must be true as well. Therefore once again, the check of name is not executed.

This will come in handy later on when you start dealing with more complex data types.

Encapsulating Variables

if statements introduce a new concept scope, which is a way to encapsulate variables through the use of braces.

Let’s take an example. Imagine you want to calculate the fee to charge your client. Here’s the deal you’ve made:

You earn $25 for every hour up to 40 hours, and $50 for every hour thereafter.

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:

1250

The interesting thing here is the code inside the if statement. There is a declaration of a new constant, hoursOver40, to store the number of hours over 40. Clearly, you can use it 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

Now I want to introduce a new operator, one you didn’t see in the previous tutorial. It’s called the ternary conditional operator and it’s related to if statements.

If you wanted to determine the minimum and maximum of two variables, you could use if statements, like so:

let a = 5
let b = 10

let min: Int
if a < b {
  min = a
} else {
  min = b
}

let max: Int
if a > b {
  max = a
} else {
  max = b
}

By now you know how this works, but it’s a lot of code. Wouldn’t it be nice if you could shrink this to just a couple of lines? Well, you can, thanks to 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>

You can use this operator to rewrite your long code block above, like so:

let a = 5
let b = 10

let min = a < b ? a : b
let max = a > b ? a : b

In the first example, the condition is a < b. If this is true, the result assigned back to min will be the value of a; if it’s false, the result will be the value of b.

I’m sure you agree that’s much simpler! This is a useful operator that you’ll find yourself using regularly.

Note: Because finding the greater or smaller of two numbers is such a common operation, the Swift standard library provides two functions for this purpose: max and min. If you were paying attention earlier in this series, then you’ll recall you’ve already seen these.

Mini-exercises

  1. Create a constant called myAge and initialize it with your age. Write an if statement to print out Teenager if your age is between 13 and 19, and Not a teenager if your age is not between 13 and 19.
  2. Create a constant called answer and use a ternary condition to set it equal to the result you print out for the same cases in the above exercise. Then print out answer.

Loops

Loops are Swift’s way of executing code multiple times. In this section, you’ll learn about one type of loop, the while loop. If you know another programming language, you’ll find the concepts and maybe even the syntax to be familiar.

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

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. Of course, you would never write such a while loop, because your program would spin forever! This situation is known as an infinite loop, and while it might not cause your program to crash, it will very likely cause your computer to freeze.

force_quit

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 where the value is greater than 1000.

The loop executes as follows:

  • Before iteration 1: sum = 1, loop condition = true
  • After iteration 1: sum = 3, loop condition = true
  • After iteration 2: sum = 7, loop condition = true
  • After iteration 3: sum = 15, loop condition = true
  • After iteration 4: sum = 31, loop condition = true
  • After iteration 5: sum = 63, loop condition = true
  • After iteration 6: sum = 127, loop condition = true
  • After iteration 7: sum = 255, loop condition = true
  • After iteration 8: sum = 511, loop condition = true
  • After iteration 9: sum = 1023, loop condition = false

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.

Repeat-while Loops

A variant of the while loop is called the repeat-while loop. It differs from the while loop in that the condition is evaluated at the end of the loop rather than at the beginning.

You construct a repeat-while loop like this:

repeat {
  <LOOP CODE>
} while <CONDITION>

Here’s the example from the last section, but using a repeat-while loop:

var sum = 1

repeat {
  sum = sum + (sum + 1)
} while sum < 1000

In this example, the outcome is the same as before. However, that isn’t always the case — you might get a different result with a different condition.

Consider the following while loop:

var sum = 1

while sum < 1 {
  sum = sum + (sum + 1)
}

And now consider the corresponding repeat-while loop, which uses the same condition:

var sum = 1

repeat {
  sum = sum + (sum + 1)
} while sum < 1

In the case of the regular while loop, the condition sum < 1 is false right from the start. That means the body of the loop won’t be reached! The value of sum will equal 1 because the loop won’t execute any iterations.

In the case of the repeat-while loop, however, sum will equal 3 because the loop will execute once.

Breaking Out of a Loop

Sometimes you want to break out of a loop early. You can do this using the break statement, which immediately stops the execution of the loop and continues on to the code after the loop.

For example, consider the following code:

var sum = 1

while true {
  sum = sum + (sum + 1)
  if sum >= 1000 {
    break
  }
}

Here, the loop condition is true, so the loop would normally iterate forever. However, the break means the while loop will exit once the sum is greater than or equal to 1000. Neat!

You’ve seen how to write the same loop in different ways, demonstrating that in computer programming, there are often many ways to achieve the same result. You should choose the method that’s easiest to read and conveys your intent in the best way possible. This is an approach you’ll internalize with enough time and practice.

Mini-exercises

  1. Create a variable named counter and set it equal to 0. Create a while loop with the condition counter < 10 which prints out counter is X (where X is replaced with counter value) and then increments counter by 1.
  2. Create a variable named counter and set it equal to 0. Create another variable named roll and set it equal to 0. Create a repeat-while loop. Inside the loop, set roll equal to Int(arc4random_uniform(6)) which means to pick a random number between 0 and 5. Then increment counter by 1. Finally, print After X rolls, roll is Y where X is the value of counter and Y is the value of roll. Set the loop condition such that the loop finishes when the first 0 is rolled.

Key Points

  • You use the Boolean data type Bool to represent true and false.
  • The comparison operators, all of which return a Boolean, are:

    Equal: ==
    Not equal: !=
    Less than: <
    Greater than: >
    Less than or equal: <=
    Greater than or equal: >=
    
  • You can use Boolean logic to combine comparison conditions.
  • Swift’s use of canonicalization ensures that the comparison of strings accounts for combining characters.
  • You use if statements to make simple decisions based on a condition.
  • You use else and else-if within an if statement to extend the decision-making beyond a single condition.
  • Short circuiting ensures that only the minimal required parts of a Boolean expression are evaluated.
  • You can use the ternary operator in place of simple if statements.
  • Variables and constants belong to a certain scope, beyond which you cannot use them. A scope inherits visible variables and constants from its parent.
  • While loops allow you to perform a certain task a number of times until a condition is met.
  • The break statement lets you break out of a loop.

First Challenges

Here are a few challenges before you head into the next section on advanced control flow:

  1. What’s wrong with the following code?
let firstName = "Matt"

if firstName == "Matt" {
  let lastName = "Galloway"
} else if firstName == "Ray" {
  let lastName = "Wenderlich"
}
let fullName = firstName + " " + lastName
  1. In each of the following statements, what is the value of the Boolean answer constant?
let answer = true && true
let answer = false || false
let answer = (true && 1 != 2) || (4 > 3 && 100 < 1)
let answer = ((10 / 2) > 3) && ((10 % 2) == 0)
  1. Suppose the squares on a chessboard are numbered left to right, top to bottom, with 0 being the top-left square and 63 being the bottom-right square. Rows are numbered top to bottom, 0 to 7. Columns are numbered left to right, 0 to 7. Given a current position on the chessboard, expressed as a row and column number, calculate the next position on the chessboard, again expressed as a row and column number. The ordering is determined by the numbering from 0 to 63. The position after 63 is again 0.
  2. Given the coefficients a, b and c, calculate the solutions to a quadratic equation with these coefficients. Take into account the different number of solutions (0, 1 or 2). If you need a math refresher, this Wikipedia article on the quadratic equation will help https://en.wikipedia.org/wiki/Quadratic_formula.
  3. Given a month (represented with a String in all lowercase) and the current year (represented with an Int), calculate the number of days in the month. Remember that because of leap years, "february" has 29 days when the year is a multiple of 4 but not a multiple of 100. February also has 29 days when the year is a multiple of 400.
  4. Given a number, determine if this number is a power of 2. (Hint: you can use log2(number) to find the base 2 logarithm of number. log2(number) will return a whole number if number is a power of two. You can also solve the problem using a loop and no logarithm.)
  5. Print a table of the first 10 powers of 2.
  6. Given a number n, calculate the n-th Fibonacci number. (Recall Fibonacci is 1, 1, 2, 3, 5, 8, 13, ... Start with 1 and 1 and add these values together to get the next value. The next value is the sum of the previous two. So the next value in this case is 8+13 = 21.)
  7. Given a number n, calculate the factorial of n. (Example: 4 factorial is equal to 1 * 2 * 3 * 4.)
  1. Given a number between 2 and 12, calculate the odds of rolling this number using two six-sided dice. Compute it by exhaustively looping through all of the combinations and counting the fraction of outcomes that give you that value. Don't use a formula.

Advanced Control Flow

In this section, you’ll continue to learn how to control the flow of execution. You’ll learn about another loop known as the for loop.

Loops may not sound very interesting, but they’re very common in computer programs. For example, you might have code to download an image from the cloud; with a loop, you could run that multiple times to download your entire photo library. Or if you have a game with multiple computer-controlled characters, you might need a loop to go through each one and make sure it knows what to do next.

You’ll also learn about switch statements which are particularly powerful in Swift. They allow you to inspect a value and decide what to do based on its value. They’re incredibly powerful when used with some advanced Swift features such as pattern matching.

Ranges

Before you dive into the for loop statement, you need to know about the Range data type, which lets you represent a sequence of numbers. Let’s look at two types of Range.

First, there’s closed range, which you represent like so:

let closedRange = 0...5

The three dots (...) indicate that this range is closed, which means the range goes from 0 to 5 inclusive. That’s the numbers (0, 1, 2, 3, 4, 5).

Second, there’s half-open range, which you represent like so:

let halfOpenRange = 0..<5

Here, you replace the three dots with two dots and a less-than sign (..<). Half-open means the range goes from 0 to 5, inclusive of 0 but not of 5. That’s the numbers (0, 1, 2, 3, 4).

Both open and half-open ranges must always be increasing. In other words, the second number must always be greater than or equal to the first.

Ranges are commonly used in both for loops and switch statements, which means that throughout the rest of this section, you’ll use ranges as well!

For Loops

In the previous section, you looked at while loops. Now that you know about ranges, it’s time to look at another type of loop: the for loop. This is probably the most common loop you’ll see, and you’ll use it to run code a certain number of times.

You construct a for loop like this:

for <CONSTANT> in <RANGE> {
  <LOOP CODE>
}

The loop begins with the for keyword, followed by a name given to the loop constant (more on that shortly), followed by in, followed by the range to loop through.

Here’s an example:

let count = 10
var sum = 0

for i in 1...count {
  sum += i
}

In the code above, the for loop iterates through the range 1 to count. At the first iteration of the loop, i will equal the first element in the range: 1. Each time around the loop, i will increment until it’s equal to count; the loop will execute one final time and then finish.

Note: If you’d used a half-open range, the the last iteration would see i equal to count - 1.

Inside the loop, you add i to the sum variable; it runs 10 times to calculate the sequence 1 + 2 + 3 + 4 + 5 + ... all the way up to 10.

Here are the values of the constant i and variable sum for each iteration:

  • Start of iteration 1: i = 1, sum = 0
  • Start of iteration 2: i = 2, sum = 1
  • Start of iteration 3: i = 3, sum = 3
  • Start of iteration 4: i = 4, sum = 6
  • Start of iteration 5: i = 5, sum = 10
  • Start of iteration 6: i = 6, sum = 15
  • Start of iteration 7: i = 7, sum = 21
  • Start of iteration 8: i = 8, sum = 28
  • Start of iteration 9: i = 9, sum = 36
  • Start of iteration 10: i = 10, sum = 45
  • After iteration 10: sum = 55

In terms of scope, the i constant is only visible inside the scope of the for loop, which means it’s not available outside of the loop.

Note: If you’re mathematically astute, you might notice that this example computes triangle numbers. Here’s a quick explanation: http://bbc.in/1O89TGP

Xcode’s playground gives you a handy way to visualize such an iteration. Hover over the sum += i line in the results pane, and you’ll see a white dot on the right. Hover over that dot to reveal a plus (+) button:

loop_before_graph

Click this plus (+) button and Xcode will display a graph underneath the line within the playground code editor:

loop_after_graph

This graph lets you visualize the sum variable as the loop iterates.

Finally, sometimes you only want to loop a certain number of times, and so you don’t need to use the loop constant at all. In that case, you can employ the underscore to indicate you’re ignoring it, like so:

let count = 10
var sum = 1
var lastSum = 0

for _ in 0..<count {
  let temp = sum
  sum = sum + lastSum
  lastSum = temp
}

This code doesn’t require a loop constant; the loop simply needs to run a certain number of times. In this case, the range is 0 through count and is half-open. This is the usual way of writing loops that run a certain number of times.

It’s also possible to only perform the iteration under certain conditions. For example, imagine you wanted to compute a sum similar to that of triangle numbers, but only for odd numbers:

let count = 10
var sum = 0
for i in 1...count where i % 2 == 1 {
  sum += i
}

The loop above has a where clause in the for loop statement. The loop still runs through all values in the range 1 to count, but it will only execute the loop’s code block when the where condition is true; in this case, where i is odd.

Continue and Labeled Statements

Sometimes you’d like to skip a loop iteration for a particular case without breaking out of the loop entirely. You can do this with the continue statement, which immediately ends the current iteration of the loop and starts the next iteration.

Note: In many cases, you can use the simpler where clause you just learned about. The continue statement gives you a higher level of control, letting you decide where and when you want to skip an iteration.

Take the example of an 8 by 8 grid, where each cell holds a value of the row multiplied by the column:

full_board

It looks much line a multiplication table, doesn’t it?

Let’s say you wanted to calculate the sum of all cells but exclude all even rows, as shown below:

first_board_example

Using a for loop, you can achieve this as follows:

var sum = 0

for row in 0..<8 {
  if row % 2 == 0 {
    continue
  }

  for column in 0..<8 {
    sum += row * column
  }
}

When the row modulo 2 equals 0, the row is even. In this case, continue makes the for loop skip to the next row.

Just like break, continue works with both for loops and while loops.

The second code example will calculate the sum of all cells, excluding those where the column is greater than or equal to the row.

To illustrate, it should sum the following cells:

second_board_example

Using a for loop, you can achieve this as follows:

var sum = 0

rowLoop: for row in 0..<8 {
  columnLoop: for column in 0..<8 {
    if row == column {
      continue rowLoop
    }
    sum += row * column
  }
}

This last code block makes use of labeled statements, labeling the two loops as rowLoop and the columnLoop, respectively. When the row equals the column inside the inner columnLoop, the outer rowLoop will continue.

You can use labeled statements like these with break to break out of a certain loop. Normally, break and continue work on the innermost loop, so you need to use labeled statements if you want to manipulate an outer loop.

Mini-exercises

  1. Create a variable called range and set it equal to a range starting at 1 and ending with 10 inclusive. Write a for loop which iterates over this range and prints the square of each number.
  2. Write a for loop which iterates over the same range as in the exercise above and prints the square root of each number. Hint: you will need to type convert your loop variable.
  3. Above, you saw a for loop which iterated over only the even rows like so:
var sum = 0
for row in 0..<8 {
  if row % 2 == 0 {
    continue
  }
  for column in 0..<8 {
    sum += row * column
  }
}

Change this to use a where clause on the first for loop to skip even rows instead of using continue. Check that the sum is 448 as in the initial example.

Switch Statements

Another way to control flow is through the use of a switch statement, which lets you execute different bits of code depending on the value of a variable or constant.

Here’s a very simple switch statement that acts on an integer:

let number = 10

switch number {
case 0:
  print("Zero")
default:
  print("Non-zero")
}

In this example, the code will print the following:

Non-zero

The purpose of this switch statement is to determine whether or not a number is zero. It will get more complex — I promise!

To handle a specific case, you use case followed by the value you want to check for, which in this case is 0. Then, you use default to signify what should happen for all other values.

Here’s another example:

let number = 10

switch number {
case 10:
  print("It's ten!")
default:
  break
}

This time you check for 10, in which case, you print a message. Nothing should happen for other values. When you want nothing to happen for a case, or you want the default state to run, you use the break statement. This tells Swift that you meant to not write any code here and that nothing should happen. Cases can never be empty, so you must write some code, even if it’s just a break!

Of course, switch statements also work with data types other than integers. They work with any data type! Here’s an example of switching on a string:

let string = "Dog"

switch string {
case "Cat", "Dog":
  print("Animal is a house pet.")
default:
  print("Animal is not a house pet.")
}

This will print the following:

Animal is a house pet.

In this example, you provide two values for the case, meaning that if the value is equal to either "Cat" or "Dog", then the statement will execute the case.

Advanced Switch Statements

You can also give your switch statements more than one case. In the previous section, you saw an if statement using multiple else-if statements to convert an hour of the day to a string describing that part of the day. You could rewrite that more succinctly with a switch statement, like so:

let hourOfDay = 12
let timeOfDay: String

switch hourOfDay {
case 0, 1, 2, 3, 4, 5:
  timeOfDay = "Early morning"
case 6, 7, 8, 9, 10, 11:
  timeOfDay = "Morning"
case 12, 13, 14, 15, 16:
  timeOfDay = "Afternoon"
case 17, 18, 19:
  timeOfDay = "Evening"
case 20, 21, 22, 23:
  timeOfDay = "Late evening"
default:
  timeOfDay = "INVALID HOUR!"
}

print(timeOfDay)

This code will print the following:

Afternoon

Remember ranges? Well, you can use ranges to simplify this switch statement. You can rewrite it using ranges as shown below:

let hourOfDay = 12
let timeOfDay: String

switch hourOfDay {
case 0...5:
  timeOfDay = "Early morning"
case 6...11:
  timeOfDay = "Morning"
case 12...16:
  timeOfDay = "Afternoon"
case 17...19:
  timeOfDay = "Evening"
case 20..<24:
  timeOfDay = "Late evening"
default:
  timeOfDay = "INVALID HOUR!"
}

This is more succinct than writing out each value individually for all cases.

When there are multiple cases, the statement will execute the first one that matches. You’ll probably agree that this is more succinct and more clear than using an if statement for this example. It’s slightly more precise as well, because the if statement method didn’t address negative numbers, which here are correctly deemed to be invalid.

It’s also possible to match a case to a condition based on a property of the value. As you learned in the first part of this tutorial series, you can use the modulo operator to determine if an integer is even or odd. Consider this code:

let number = 10

switch number {
case let x where x % 2 == 0:
  print("Even")
default:
  print("Odd")
}

This will print the following:

Even

This switch statement uses the let-where syntax, meaning the case will match only when a certain condition is true. The let part binds a value to a name, while the where part provides a Boolean condition that must be true for the case to match. In this example, you’ve designed the case to match if the value is even — that is, if the value modulo 2 equals 0.

The method by which you can match values based on conditions is known as pattern matching.

In the previous example, the binding introduced a unnecessary constant x; it’s simply another name for number. You are allowed to use number in the where clause and replace the binding with an underscore to ignore it:

let number = 10

switch number {
case _ where number % 2 == 0:
  print("Even")
default:
  print("Odd")
}

Partial Matching

Another way you can use switch statements with matching to great effect is as follows:

let coordinates = (x: 3, y: 2, z: 5)

switch coordinates {
case (0, 0, 0): // 1
  print("Origin")
case (_, 0, 0): // 2
  print("On the x-axis.")
case (0, _, 0): // 3
  print("On the y-axis.")
case (0, 0, _): // 4
  print("On the z-axis.")
default:        // 5
  print("Somewhere in space")
}

This switch statement makes use of partial matching. Here’s what each case does, in order:

  1. Matches precisely the case where the value is (0, 0, 0). This is the origin of 3D space.
  2. Matches y=0, z=0 and any value of x. This means the coordinate is on the x-axis.
  3. Matches x=0, z=0 and any value of y. This means the coordinate is on the y-axis.
  4. Matches x=0, y=0 and any value of z. This means the coordinate is on the z-axis.
  5. Matches the remainder of coordinates.

You’re using the underscore to mean that you don’t care about the value. If you don’t want to ignore the value, then you can bind it and use it in your switch statement, like this:

let coordinates = (x: 3, y: 2, z: 5)

switch coordinates {
case (0, 0, 0):
  print("Origin")
case (let x, 0, 0):
  print("On the x-axis at x = \(x)")
case (0, let y, 0):
  print("On the y-axis at y = \(y)")
case (0, 0, let z):
  print("On the z-axis at z = \(z)")
case let (x, y, z):
  print("Somewhere in space at x = \(x), y = \(y), z = \(z)")
}

Here, the axis cases use the let syntax to pull out the pertinent values. The code then prints the values using string interpolation to build the string.

Notice how you don’t need a default in this switch statement. This is because the final case is essentially the default; it matches anything, because there are no constraints on any part of the tuple. If the switch statement exhausts all possible values with its cases, then no default is necessary.

Also notice how you could use a single let to bind all values of the tuple: let (x, y, z) is the same as (let x, let y, let z).

Finally, you can use the same let-where syntax you saw earlier to match more complex cases. For example:

let coordinates = (x: 3, y: 2, z: 5)

switch coordinates {
case let (x, y, _) where y == x:
  print("Along the y = x line.")
case let (x, y, _) where y == x * x:
  print("Along the y = x^2 line.")
default:
  break
}

Here, you match the “y equals x” and “y equals x squared” lines.

And those are the basics of switch statements!

Mini-exercises

  1. Write a switch statement that takes an age as an integer and prints out the life stage related to that age. You can make up the life stages, or use my categorization as follows: 0-2 years, Infant; 3-12 years, Child; 13-19 years, Teenager; 20-39, Adult; 40-60, Middle aged; 61+, Elderly.
  2. Write a switch statement that takes a tuple containing a string and an integer. The string is a name, and the integer is an age. Use the same cases that you used in the previous exercise and let syntax to print out the name followed by the life stage. For example, for myself it would print out "Matt is an adult.".

Key Points

  • You can use ranges to create a sequence of numbers, incrementing to move from one value to another.
  • Closed ranges include both the start and end values.
  • Half-open ranges include the start value and stop one before the end value.
  • For loops allow you to iterate over a range.
  • The continue statement lets you finish the current iteration of a loop and begin the next iteration.
  • Labeled statements let you use break and continue on an outer loop.
  • You use switch statements to decide which code to run depending on the value of a variable or constant.
  • The power of a switch statement comes from leveraging pattern matching to compare values using complex rules.

Give these challenges a try to see if you fully understand the subtleties of loop and switch statements.

Second Challenges

  1. In the following for loop:
var sum = 0
for i in 0...5 {
  sum += i
}

What will be the value of sum, and how many iterations will happen?

  1. In the while loop below:
var aLotOfAs = ""
while aLotOfAs.characters.count < 10 {
  aLotOfAs += "a"
}

How many instances of the character “a” will there be in aLotOfAs? Hint: aLotOfAs.characters.count will tell you how many characters there are in the string aLotOfAs.

  1. Consider the following switch statement:
switch coordinates {
case let (x, y, z) where x == y && y == z:
  print("x = y = z")
case (_, _, 0):
  print("On the x/y plane")
case (_, 0, _):
  print("On the x/z plane")
case (0, _, _):
  print("On the y/z plane")
default:
  print("Nothing special")
}

What will this code print when coordinates is each of the following?

let coordinates = (1, 5, 0)
let coordinates = (2, 2, 2)
let coordinates = (3, 0, 1)
let coordinates = (3, 2, 5)
let coordinates = (0, 2, 4)
  1. A closed range can never be empty. Why?
  2. Print a countdown from 10 to 0. (Note: do not use the reversed() method, which will be introduced later.)
  3. Print 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0. (Note: do not use the stride(from:by:to:) function, which will be introduced later.)

Where to Go From Here?

You’ve learned a lot about the core language features for dealing with data over these past few tutorials — from data types to variables, then on to decision-making with Booleans and loops with ranges.

You can download the final playgrounds and challenges from the first part and second part of this tutorial here.

We encourage you to try the challenges above; if you find a particularly interesting solution to one of the challenges, or have any questions or comments on this tutorial, please tell us about it in the discussion below!

swift-apprentice

This tutorial was taken from Chapters 4 and 5 of Swift Apprentice, Second Edition available from the raywenderlich.com store.

The book has been completely updated to work with Xcode 8 and Swift 3. Check it out and let us know what you think!

Matt Galloway

Matt is the founder of SwipeStack, a mobile development company based in London, UK which create apps for clients and also a few of their own. One client's app was featured by Apple in the best apps of 2011, the App Rewind in the newsstand category.

BeerMap is one of their own creations, helping beer drinkers find a great pub near them! You can find him on Twitter.

Other Items of Interest

Save time.
Learn more with our video courses.

raywenderlich.com Weekly

Sign up to receive the latest tutorials from raywenderlich.com each week, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

PragmaConf 2016 Come check out Alt U

Our Books

Our Team

Video Team

... 20 total!

Swift Team

... 15 total!

iOS Team

... 44 total!

Android Team

... 14 total!

macOS Team

... 11 total!

Unity Team

... 11 total!

Articles Team

... 12 total!

Resident Authors Team

... 16 total!