Loops (for, while, repeat-while) - Swift Tutorial

Ozan Emre Duran
AppleCode Chronicles
2 min readJun 6, 2023

Swift, a programming language developed by Apple, provides several loop constructs for repetitive execution of code. The three main types of loops in Swift are:

For Loop: The for loop is used when you know the number of iterations in advance. It iterates over a sequence, such as a range of numbers or an array, and executes a block of code for each item in the sequence.

for item in sequence {
// Code to be executed for each item
}

Here, item represents the current item in the sequence, and sequence is the collection over which the loop iterates. You can perform operations on each item within the loop body.

While Loop: The while loop repeatedly executes a block of code as long as a specified condition is true. It evaluates the condition before each iteration.

while condition { 
// Code to be executed
}

The loop continues executing the code block until the condition becomes false. If the condition is initially false, the loop body won’t execute at all.

Repeat-While Loop: The repeat-while loop is similar to the while loop, but it evaluates the condition after each iteration. This guarantees that the loop body executes at least once.

repeat { 
// Code to be executed
} while condition

The code block executes first, and then the condition is checked. If the condition is true, the loop continues executing; otherwise, the loop terminates.

Here are a couple of examples to demonstrate the usage of these loops in Swift:

Example 1:

for number in 1...5 { 
print(number)
}

Output:

1 
2
3
4
5

Example 2:

var i = 1 
while i <= 5 {
print(i) i += 1
}

Output:

1 
2
3
4
5

Example 3:

var j = 1 
repeat {
print(j)
j += 1
} while j <= 5

Output:

1 
2
3
4
5

These examples demonstrate basic usage, but you can incorporate complex conditions, control flow statements, and other operations within the loop bodies to achieve different behaviors as per your requirements.

If you’re interested in learning more about Swift, I recommend checking out my articles on Medium. You can access them through the template I created on Notion, which provides a structured learning process and easy navigation to different topics. Happy learning, and best of luck on your Swift programming journey!

Click here for Notion Swift Tutorial Template :)

--

--

Ozan Emre Duran
AppleCode Chronicles

I'm a passionate programmer who loves exploring and using Apple products. Swift is my language of choice.