Looping n Times in Swift

When you need to repeat a piece of code a specific number of times in Swift, there are multiple approaches to achieve this.

In this post, I’ll show you two common approaches using the for-in loop and the forEach method. Additionally, for those who appreciate a more Ruby-like approach, I’ll show you how to create a custom extension to mimic the times method.

Using for-in Loop

The for-in loop with the closed range operator (...) is a straightforward way to convey the intention of looping n times.

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

This loop will execute the code block five times, printing the values from 1 to 5.

Output:

1
2
3
4
5

If you don’t need the loop variable i, you can use an underscore _:

for _ in 1...5 {
    print("Hello!")
}

This loop will print “Hello!” five times.

Output:

Hello!
Hello!
Hello!
Hello!
Hello!

Using forEach

The forEach function can also be employed to achieve the same effect. Here’s an example:

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

This accomplishes the same result as the for-in loop, iterating over the values from 1 to 5.

Output:

1
2
3
4
5

Adding a Ruby-like Extension

For those who appreciate a more Ruby-like syntax, you can create a custom extension to mimic the times method. While this may not be a common practice, it’s an interesting exercise to demonstrate Swift’s flexibility.

extension Int {
    func times(_ callback: (Int) -> ()) {
        if self > 0 {
            for i in 0..<self {
                callback(i)
            }
        }
    }
}

Now, you can use it as follows:

5.times { i in
    print(i)
}

This extension allows you to loop a specific number of times using a syntax similar to Ruby’s times method.

Output:

0
1
2
3
4

Remember, while such extensions might be fun, they should be used judiciously to avoid unnecessary complexity in your codebase.

Experiment with these methods and choose the one that best fits your coding style and the specific requirements of your project. Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top