OneBite.Dev - Coding blog in a bite size

Loop Object In Swift

Code snippet for how to Loop Object In Swift with sample and detail explanation

Looping in Swift is a fundamental concept that is a part of nearly every program you will likely encounter. Understanding loops, whether it’s a for-in, while, or repeat-while loop, is essential to controlling the flow and execution of your code.

Code snippet for a For-In Loop

Here is a simple code snippet of a for-in loop in Swift:

for number in 1...5 {
    print("Number is \(number)")
}

Code Explanation for a For-In Loop

The basic idea of a for-in loop is that it executes a set of instructions for a certain number of times. The above Swift code is a perfect example. Let’s break it down, step by step:

  • for number in 1...5: Here we declare a Swift range from 1 to 5, that creates a sequence of numbers 1, 2, 3, 4, 5. Then for each number in this sequence, the loop will execute.

  • print("Number is \(number)"): This line is the instruction that will be executed for each number in the sequence. This particular line prints the statement “Number is X”, where X is the current number in the sequence.

So, each time the loop executes, it takes the next number in the sequence. It starts with 1 since that’s the first number in the range.

On the first iteration, it prints “Number is 1”. Then it moves onto the next number, 2, and prints “Number is 2”. This continues until the sequence is completed and there are no more numbers left. At the end, you should see the numbers 1 through 5 printed out in your console, each on a new line.

This particular for-in loop iterates five times because there’re five numbers in the range. If you wanted the loop to execute ten times, you would simply change the range to 1...10.

swift