6 min read

In the article by, Craig Clayton, author of the book, iOS 10 Programming for Beginners, we went over the basics of Swift to get you warmed up. Now, we will dig deeper and learn some more programming concepts. These concepts will build on what you have already learned. In this article, we will cover the following topics:

  • Ranges
  • Control flow

(For more resources related to this topic, see here.)

Creating a Playground project

Please launch Xcode and click on Get started with a playground.

The options screen for creating a new playground screen will appear:

Please name your new Playground SwiftDiggingDeeper and make sure that your Platform is set to iOS. Now, let’s delete everything inside of your file and toggle on the Debug panel using either the toggle button or Cmd + Shift + Y. Your screen should look like mine:

Ranges

These generic data types represent a sequence of numbers. Let’s look at the image below to understand:

Closed range

Notice that, in the image above, we have numbers ranging from 10 to 20. Rather than having to write each value, we can use ranges to represent all of these numbers in shorthand form. In order to do this, let’s remove all of the numbers in the image except 10 and 20.

Now that we have removed those numbers, we need a way to tell Swift that we want to include all of the numbers that we just deleted. This is where the range operator () comes into play. So, in Playgrounds, let’s create a constant called range and set it equal to 10…20:

let range = 10...20

The range that we just entered says that we want the numbers between 10 and 20 as well as both 10 and 20 themselves. This type of range is known as a closed range. We also have what is called a half closed range.

Half closed range

Let’s make another constant called half closed range and set it equal to 10..<20:

let halfClosedRange = 10..<20

A half closed range is the same as a closed range except that the end value will not be included. In this example, that means that 10 through 19 will be included and 20 will be excluded.

At this point, you will notice that your results panel just shows you CountableClosedRange(10…20) and CountableRange(10..<20). We cannot see all the numbers within the range. In order to see all the numbers, we need to use a loop.

Control flow

In Swift, we use a variety of control statements.

For-In Loop

One of the most common control statements is a for-in loop. A for-in loop allows you to iterate over each element in a sequence. Let’s see what a for-loop looks like:

for <value> in <sequence>  {
  // Code here
}

So, we start our for-in loop with for, which is followed by <value>. This is actually a local constant (only the for-in loop can access it) and can be any name you like. Typically, you will want to give this value an expressive name. Next, we have in, which is followed by <sequence>. This is where we want to give it our sequence of numbers. Let’s write the following into Playgrounds:

for value in range  {
  print("closed range - (value)")
}

Notice that, in our debug panel, we see all of the numbers we wanted in our range:

Let’s do the same for our variable halfClosedRange by adding the following:

for index in halfClosedRange  {
  print("half closed range - (index)")
}

In our debug panel, we see that we get the numbers 10 through 19. One thing to note is that these two for-in loops have different variables. In the first loop, we used value, and in the second one, we used index. You can make these whatever you choose.

In addition, in the two examples, we used constants, but we could actually just use the ranges within the loop. Please add the following:

for index in 0...3  {
  print("range inside - (index)")
}

Now, you will see 0 to 3 print inside the debug panel:

What if you wanted numbers to go in reverse order? Let’s input the following for-in loop:

for index in (10...20).reversed()  {
  print("reversed range - (index)")
}

We now have the numbers in descending order in our debug panel. When we add ranges into a for-in loop, we have to wrap our range inside parentheses so that Swift recognizes that our period before reversed() is not a decimal.

The while Loop

A while loop executes a Boolean expression at the start of the loop, and the set of statements run until a condition becomes false. It is important to note that while loops can be executed zero or more times. Here is the basic syntax of a while loop:

while <condition>  {
  // statement
}

Let’s write a while loop in Playgrounds and see how it works. Please add the following:

var y = 0
while y < 50 {
  y += 5
  print("y:(y)")
}

So, this loop starts with a variable that begins at zero. Before the while loop executes, it checks to see if y is less than 50; and, if so, it continues into the loop. By using the += operator, we increment y by 5 each time. Our while loop will continue to do this until y is no longer less than 50. Now, let’s add the same while loop after the one we created and see what happens:

while y < 50 {
  y += 5
  print("y:(y)")
}

You will notice that the second while loop never runs. This may not seem like it is important until we look at our next type of loop.

The repeat-while loop

A repeat-while loop is pretty similar to a while loop in that it continues to execute the set of statements until a condition becomes false. The main difference is that the repeat-while loop does not evaluate its Boolean condition until the end of the loop. Here is the basic syntax of a repeat-while loop:

repeat {
  // statement
} <condition> 

Let’s write a repeat-while loop in Playgrounds and see how it works. Type the following into Playgrounds:

var x = 0
repeat {
  x += 5
  print("x:(x)")
} while x < 100
print("repeat completed x: (x)")

So, our repeat-while loop executes first and increments x by 5, and afterwards (as opposed to checking the condition before as with a while loop), it checks to see if x is less than 100. This means that our repeat-while loop will continue until the condition hits 100. But here is where it gets interesting. Let’s add another repeat-while loop after the one we just created:

repeat {
  x += 5
  print("x:(x)")
} while x < 100
print("repeat completed again x: (x)")

This time, the repeat…while loop incremented to 105. This happens because the Boolean expression does not get evaluated until after it is incremented by 5. Knowing this behavior will help you pick the right loop for your situation.

So far, we have looked at three loops: the for-in loop, the while loop, and the repeat-while loop. We will use the for-in loop again, but first we need to talk about collections.

Summary

The article summarizes Ranges and control flow using Xcode 8.

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here