Swift: The for-in Loop

for-in Loop in Swift:

Let’s start with the for-in loop in Swift now that we know what loops can do for us. The general syntax is as follows:

for variable in sequence {
  for-in loop body
}

Iterating over a sequence of values, such as Strings (a sequence of characters) or ranges, is done with for-in loops (sequence of numbers). We use the closed range operator (...) with a lower bound number and an upper bound number to make a range. For example, the numbers 1, 2, and 3 are contained in a range of 1...3 with a lower bound of 1 and an upper bound of 3.

Let’s say we wanted to use a for-in loop to iterate (repeat tasks) while going through the range: 4...7, which represents the sequence of numbers 4, 5, 6, and 7.

print("Why is 4 frightened of 5? Because...");
for numbers in 4...7 {
  print(numbers);
}

Let’s analyse the above example:

  • The loop starts with the for keyword.
  • The current iteration’s value is stored in a variable named as numbers. It’s worth noting that we don’t declare it with a keyword like var; instead, the Swift compiler does it for us. It can be thought of as a placeholder, as the placeholder (numbers) has a value of 4 during the first iteration.
  • The placeholder is separate from the iteration sequence by the in keyword.
  • The sequence we’re iterating over is 4...7, which is a range containing the numbers 4, 5, 6, and 7.
  • Curly braces {} encircle the body of the forin loop.

After considering the syntax, it should come as no surprise that our code snippet prints out:

Why is 4 frightened of 5? Because...
4
5
6
7

Do you get it? It’s because 5 sounds like fire too. Now, let’s get back to programming… ðŸ˜…

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: