How to Create a For-In Loop in Swift

swift-logo-200x200.png

There are many times when writing an app that you will need to loop through some data, numbers, an array, recorded game scores etc. To do this you can use a loop.

In this lesson I will show you how to create a simple for-in loop.

STEP 1

Open Xcode and create a new playground.

Xcode Welcome Screen.png

STEP 2

Select a blank iOS template.

Blank iOS Template Screen.png

STEP 3

Give your playground a name and save it to your desired location. I usually select the Desktop if it is nothing I want to keep. Otherwise, I place important files into a Swift folder. Here I have called mine ‘loops’.

loops.png

STEP 4

You will notice that Xcode creates a sample piece of code as follows:

Xcode default code.png

STEP 5

Remove the default code as it is not required for what you are doing.

STEP 6

You will now create some code to list the numbers 1 to 10.

The format of the for-in loop is fairly easy.

LINE 1: we create the for-in loop with a variable called number. Notice the 3 dots between the numbers 1 and 10. This just means that we want all of the numbers from 1 to 10 inclusive. We then open a curly brace

LINE 2: we print the number. Since we are looping from 1 to 10, all these numbers will be printed.

LINE 3: we close the curly brace. Everything inside the curly braces is executed each time through the loop.

STEP 7

What is you wanted to print the numbers 1 to 10 but in reverse order? So, 10 down to 1. The code would look like this:

LINE 1: we still count from 1 to 10 but we apply the reversed() function to the numbers.

STEP 8

Now let us consider a loop within a loop. This is called a nested loop. An interesting one is to print out the multiplication tables.

1 x 1 = 1

1 x 2 = 2

1 x 3 = 3

…etc

LINE 1: we create the first loop with a variable called number1 with values between 1 and 10 inclusive

LINE 2: we create a second loop with a variable called number2 with values between 1 and 10 inclusive

LINE 3: we multiply number1 and number2 and store the result in the variable called answer

LINE 4: we perform a little bit of concatenation. Since we are dealing with integer values and some strings we need to apply the String() function to the numbers so that we get the desired output. You will get an error if you do not convert as Swift will not let you concatenate string and integers.

LINE 6: This line will just print a line break between each set of multiplication tables.

The output is as follows:

DID YOU FIND THIS LESSON USEFUL?

If you wish to learn to code then consider joining the Learn to Code courses.