Cycles or loops in Swift: for in, while and repeat-while

- Andrés Cruz

ES En español

Cycles or loops in Swift: for in, while and repeat-while

Today we are going to talk about another basic element in any programming language: cycles, or also called loops. As you should know, these allow you to execute a group of iterations over a block of code a specific number of times. This number of repetitions is established or marked by a condition, similar to the conditionals in Swift that we covered in the previous post.

When you start programming in Swift, one of the first concepts you absolutely need to master is cycles or loops. They are a key piece of control flow and allow you to execute the same block of code multiple times, whether it's a specific number of iterations or until a condition is met.

In my case, understanding loops well from the beginning saved me many typical mistakes and helped me write cleaner, easier-to-maintain code. In this article, we are going to look at the most important loops in Swift —for-in, while, and repeat-while— with clear and practical examples.

What are cycles or loops in Swift and what are they for?

Cycles or loops in Swift allow you to repeat a set of instructions without having to write the same code over and over again. This is fundamental for:

  • Iterating through arrays and collections
  • Processing ranges of values
  • Repeating tasks until a condition is met
  • Controlling a program's flow efficiently

Swift includes several types of loops, each designed for a specific scenario. Choosing the right one makes the difference between clear code and code that is hard to understand.

Types of loops in Swift

In Swift, we primarily work with three types of loops:

  • for-in
  • while
  • repeat-while

Let's look at them one by one.

Although, as we will see, each of them has its variation that we will discuss below:

The for-in loop in Swift

There are many variations you can apply to a for-type loop; generally, they are all followed by in, which then allows us to specify the type of structure we can iterate over. These can range from numerical ranges to arrays, all with their variations and the possibility of combining all the patterns we bring you here; remember that we are presenting the most common patterns, but more exist.

The loop could be seen as the simplest to understand, as it comes with a well-defined and easy-to-grasp structure; in it, we specify the number of interactions we want to perform, marking the initial element and then the final element, increasing by one by default:

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

Here we get as output:

12345

Using for-in with numerical ranges

Swift offers very powerful range operators:

  • ... → closed range (includes both endpoints)
  • ..< → half-open range (excludes the final value)

In the previous example, we showed a variable called i that takes 1 as its first value, since that is the first value of the range 1...5, and as it executes, this value increases by one until it reaches the end of the range, which for this example would be 5.

Inside it, we can place any type of logic we want; for example, if we want to distinguish between even and odd values:

for i in 1...10 {
    if i%2 == 0{
        print("Es par \(i)")
    } else {
        print("Es impar \(i)")
    }
}

The result would be:

It is odd 1 
It is even 2 
It is odd 3 
It is even 4 
It is odd 5 
It is even 6 
It is odd 7 
It is even 8 
It is odd 9 
It is even 10

This is the default structure and is usually used to iterate over collections such as lists or arrays.

For-in and where

Now, suppose we have a list or a very large range, and we only want to process some items and not the entire collection to save computing resources, based on a conditional as we explained in the previous post. So, how do we make the for only execute based on a condition? For that, we can use the where structure as seen below, where only even values will be shown:

for i in 1...10 where i % 2 == 0{
    print("Es par \(i)")
}

The result would be:

It is even 2 
It is even 4 
It is even 6 
It is even 8 
It is even 10

As you can see, we simply incorporate a conditional structure, just as we explained in the previous video.

For loops in reverse order and custom values (reversed and stride)

Now, suppose we are interested in processing a list backwards. Although this is a function of ranges, it is important to know that we can also make this kind of definition when we are creating a for in Swift:

for i in stride(from: 0, to: 10, by: 2) {
   print("Val \(i)")
}

The result would be:

Val 5 
Val 4 
Val 3 
Val 2 
Val 1

And if you need custom increments, you can use stride:

for i in stride(from: 5, to: 0, by: -1) {
   print("Val \(i)")
}

Or even iterate through decreasing values:

for i in stride(from: 5, to: 0, by: -1) {
    print("Val \(i)")
}

These options are very powerful and avoid extra logic inside the loop.

For-in decreasing values

If we want to go from highest to lowest, we can implement a structure like the following in which we decrease values from 5 to 1:

for i in stride(from: 5, to: 0, by: -1) {
    print("Val \(i)")
}

The result would be:

Val 5
Val 4
Val 3
Val 2
Val 1

For-in incrementing by custom values

We can also customize how much our variable will increment or decrement using the stride function as follows:

for i in stride(from: 0, to: 10, by: 2) {
    print("Val \(i)")
}

The result would be:

Val 0 
Val 2 
Val 4 
Val 6 
Val 8

Iterating through arrays with for-in

As we indicated at the beginning of the post, the most common use we can give to for loops is to iterate through a list or array object, as shown in the following case:

let numeros = [5, 10, 15, 20, 25, 30, 100]

for i in numeros {
    print("Val \(i)")
}

We can also vary its implementation as follows:

numbers.forEach { i in
    print("Val \(i)")
}

The result would be:

Val 5
Val 10
Val 15
Val 20
Val 25
Val 30
Val 100

For-in with conditions using where

When working with large collections, you don't always want to process every element. In these cases, using where directly in the loop is an elegant and efficient solution.

For example, to show only even numbers:

for i in 1...10 where i % 2 == 0 {
   print("It is even \(i)")
}

This approach avoids unnecessary conditionals inside the loop and makes the code much more readable. Personally, it's one of the features I use most when I want to filter data quickly.

Getting the index and the value

We can customize our for loop so that it also indicates the iteration index, in addition to its value:

for (index, i) in numbers.enumerated()  {
    print("Val \(i) - Indice \(index)")
}

This is especially useful when working with lists representing positions, states, or configurations.

The result would be:

Val 5 - Index 0 
Val 10 - Index 1 
Val 15 - Index 2 
Val 20 - Index 3 
Val 25 - Index 4 
Val 30 - Index 5 
Val 100 - Index 6

The while loop in Swift

For the while loop or cycle in Swift, it is practically the same as in any programming language; we have a couple of variations: the traditional while and the so-called do-while, or here in Swift, it would be repeat-while:

while

The basic structure of while is that as long as a condition is met, it will continue to execute. Unlike for, where we can see a well-specified number of interactions, here we cannot:

while val > 10 {
    print(val)
    val += 1
}

And we get as a result:

0
1
2
3
4
5
6
7
8
9

Now, if we set the following configuration:

var val = 10

while val > 10 {
    print(val)
    val += 1
}

The cycle does not execute, since the first thing the while does is verify if the condition applies. As we saw in the previous case, this is false from the start because 10 is not less than 10, and therefore the cycle ends before starting. But if we need it to execute at least once regardless of the initial condition, we can use the following structure.

Here the condition is evaluated before each iteration. If the condition is false from the start, the loop does not execute even once.

How while works and when to use it

In my experience, while is ideal for:

  • Processes that depend on states
  • Reading data until something happens
  • Logic based on dynamic conditions

Of course, you have to be careful with infinite loops if the condition never changes.

Practical examples of while in Swift

A very common example is controlling levels or states:

var currentLevel = 0
let finalLevel = 5
while currentLevel <= finalLevel {
   print("You have passed level \(currentLevel)")
   currentLevel += 1
}

The repeat-while loop in Swift

The repeat-while is similar to while, with one key difference:
the block is executed at least once, regardless of the initial condition.

var val = 10

repeat {
    print(val)
    val += 1
} while val > 10 

And we get as output:

10

As you can see, it's the same syntax, we just move the while verification to the end and place the reserved word repeat at the beginning.

If we start from the initial example, where val had a value of zero, we will see it's the same output, because when val reaches the value of 10, immediately the next line of code executed is the while verification:

var val = 10

repeat {
    print(val)
    val += 1
} while val > 10 

The output will be:

0 1 2 3 4 5 6 7 8 9

This is very useful when you need to perform an initial action before checking the condition.

  • Differences between while and repeat-while
  • Feature    while    repeat-while
  • Evaluates condition    At the beginning    At the end
  • Minimum execution    0 times    1 time
  • Typical use    Controlled iterations    Initial validations

Real cases where repeat-while is the best option

I have used repeat-while in:

  • Interactive menus
  • Input validations
  • Processes that must run at least once

In these scenarios, using a traditional while forces you to duplicate logic.

For vs while in Swift: which one to use in each case?

  • Use for-in when:
    • You know the number of iterations
    • You are iterating over collections or ranges
  • Use while when:
    • You don't know how many times the loop will run
    • You depend on a dynamic condition
  • Use repeat-while when:
    • You need at least one guaranteed execution

Choosing the right loop makes your code clearer and more maintainable.

Common mistakes when working with loops in Swift

Some typical errors I've seen (and committed):

  • Creating infinite loops by not updating the condition
  • Using forEach when you need break
  • Confusing closed ranges (...) with half-open ranges (..<)
  • Accessing indices outside the array

Detecting them in time avoids many bugs.

Frequently asked questions about loops in Swift

  • What types of loops exist in Swift?
    • Mainly for-in, while, and repeat-while.
  • What is the difference between for and while in Swift?
    • for is used when you know the number of iterations; while when it depends on a condition.
  • What is stride in Swift?
    • It is a function that allows you to iterate through ranges with custom increments.
  • Can you iterate through arrays backwards in Swift?
    • Yes, using reversed() or stride.

Conclusion: mastering loops in Swift

Cycles or loops in Swift are fundamental for any developer. Understanding for-in, while, and repeat-while well will allow you to write more efficient, readable, and safe code.

If you master these concepts from the beginning, advancing in Swift becomes much easier.

A complete guide to loops in Swift. Learn how to use for, while, and repeat-while with real-world, easy-to-understand examples.

I agree to receive announcements of interest about this Blog.

Andrés Cruz

ES En español