OneBite.Dev - Coding blog in a bite size

Do A For Loop In Swift

Code snippet for how to Do A For Loop In Swift with sample and detail explanation

Swift is a powerful and user-friendly programming language used for development in Apple’s ecosystem. Among its many features, the ‘for loop’ is a particularly useful tool that we will discuss in detail below.

Code snippet for a For Loop in Swift

Let’s consider the following code snippet as an example:

for index in 1...5 {
    print("This is iteration number \(index)")
}

This is a simple and basic example of how a for loop functions in Swift, looping five times and printing a message with each iteration.

Code Explanation for a For Loop in Swift

In this section, we deconstruct our example step-by-step.

The for-in construct is an easy way to iterate over a sequence (like a range of numbers or items in an array).

index in 1...5 – from this first part of the loop, we can see that the loop will iterate five times. The variable index will hold the current value during each iteration of the loop, from 1 to 5.

print("This is iteration number \(index)") – this is the body of the loop. It executes once for each iteration. The print statement outputs the string “This is iteration number” followed by the current value of the iteration stored in index.

With every iteration of the loop, it will print:

This is iteration number 1
This is iteration number 2
This is iteration number 3
This is iteration number 4
This is iteration number 5

After the last iteration, the loop ends and the flow of control moves to the next line of code outside the for loop.

Swift’s for-in loop is a powerful way to perform actions multiple times, with a simple and clean syntax. This feature makes it a nice asset in the arsenal of any developer working with Swift, providing efficiency and legibility in your coding projects.

swift