Start learning free

LESSON 119 OF 349 · WHILE LOOPS & FOR LOOPS

For Loop II in Swift in Swift

Lesson

There is a more powerful way to use the for loop in Swift.

For loops can be declared with a variable and a range to iterate over:

for variable in range {
	instruction1
	instruction2
	...
}

Let's break down each component:

  • The variable takes on each successive value in the range, starting from the first value. It is set up automatically before the loop begins.

  • The range defines the sequence of values the loop iterates over. The loop continues as long as there are remaining values in the range.

  • After each iteration the variable automatically advances to the next value in the range, prior to the next check.


Example:

for i in 0..<4 {
	print("Hello world!")
}

// This code prints "Hello world!" on four different lines

Let's break down this code:

  • The range starts at 0. The loop variable i is initialized to 0 so the loop starts counting from 0.

  • The range is 0..<4, meaning the loop will run as long as the iterator variable, i, is less than 4.

  • After each iteration i automatically advances to the next value. This means that after running the code inside {}, i will get increased by 1.


This is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable i = 0

1. First iteration:
	a. Is i < 4 true? <=> Is 0 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello World".
	c. i advances => i = 1

2. Second iteration:
	a. Is i < 4 true? <=> Is 1 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello World".
	c. i advances => i = 2

3. Third iteration:
	a. Is i < 4 true? <=> Is 2 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello World".
	c. i advances => i = 3

4. Forth iteration:
	a. Is i < 4 true? <=> Is 3 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello World".
	c. i advances => i = 4

5. Fifth iteration:
	a. Is i < 4 true? <=> Is 4 < 4 true? No.
	b. Exit the loop.

Assignment

Let's print "I promise to learn coding." 5 times using a for loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    The For Loop in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free