For Loop In Swift Explained

For Loop In Swift Explained

Many times when you’re creating the App, you will find yourself needing to repeat pieces of code. For instance, if we want to print “Hello World” five times, we could simply write a print statement five times. It will definitely print out the text. But is this code effective?

Now imagine that we want to print thousands of statements, which would be really annoying. Instead of just wasting our time we can simply use the For-In Loop to iterate over a collection of values. I’m sure you will all agree that it’s better than the traditional approach.


Control Flow Structure

First of all, let’s take a closer look at the format and the structure how the For Loop works in Swift programming language. As you can clearly see from the diagram first we need to write for keyword, followed by any variable name. Then comes the in keyword and the name of the collection or the range in which we want to iterate values. Finally, inside the curly braces, we’ll write the code that we want to execute multiple times.

for variableName in collection {
      // Executing Code
}

The following code will go into the collection and iterate over each element. If there are no elements left then it will exit the loop and stop the execution.

Control Flow Structure
For-In Loop Control Flow Structure

Generally, there are two types of For Loops: One that iterates through numbers and another that iterates through a data structure. So now let see a practical implementation of For Loops.

Loop through Defined Range

For-In loop allows you to iterate over a series of numbers in some range and that range you denote by the starting and the ending number.

for numbers in 1…10  {
  print(numbers)
}

If you run this line of code you will be able to see that it immediately prints numbers from 1 to 10. So what happens here?

Our For Loop gives the instruction to Xcode to print every single number in the range from 1 to 10. Now if we change the range from 10 to 20 then it will print numbers from 10 to 20. This is how For-In Loop works in Swift.

In case if you are just printing the statement in the console multiple times, where you don’t care which iteration loop is currently at. You can simply use the underscore character instead of variableName.

for _ in 1…10  {
  print(“Hello World”)
}

Range Operators in Swift

There are three different types of operators, which we use to define the start and the end point of our range.

OperatorStructureExample
Closed Range OperatorThe start
 and the end values are both included.
(a…b)
Half-Open Range OperatorGives the values from the start, up to the ending point. The last value is not included.(a..<b)
One-Sided Ranges1. Gives the values from the starting point, up to the number of elements
2. Returns the values from the starting point up to the given value
a…
…a

Those operators are extremely usefully while working with loops. They are basically shortcuts for working with a different range of values.

Print out Even Numbers with Loop

If you want to print out all the even numbers then we can use the stride function. The stride basically knows the starting and end position as well as the value that you skipping by. So we’re starting from zero, going to ten and we’re skipping by 2. This particular stride feature allows us to print all the even numbers from 0 to 10.

for number in stride(from: 0,  to: 10, by: 2) {
      print(number)
}

The stripe function is very nifty when you want to increment by a specific number. It also works in a very similar way if you want to decrement the numbers. For Instance:

for number in stride(from: 10,  to: 0, by: -2) {
      print(number)
}

Iterating over Arrays

Imagine that you have the array with a hundred elements and in order to access the data inside we have to do a very tedious task. Thankfully we can use the Loop to iterate over the elements inside the array. 

In this example, we are going to iterate over the list of airports by accessing every single object in the array.

var listOfAirports = ["London Heathrow Airport", "Frankfurt Airport", "John F. Kennedy International Airport"]

for airports in listOfAirports {
    print(airports)
}

// Prints
London Heathrow Airport 
Frankfurt Airport 
John F. Kennedy International Airport

Iterating over Dictionary

Now that we know how to iterate over an array we can also do exactly the same thing with a dictionary. Plus if we want to be more specific we can separately access both keys and values inside the dictionary. 

var listOfAirports = ["LHR": "London Heathrow Airport", "FRA": "Frankfurt Airport", "JFK": "John F. Kennedy International Airport"] 

for airports in listOfAirports { 
    print("\(airports.key): \(airports.value)") 
}

// Prints
LHR: London Heathrow Airport 
JFK: John F. Kennedy International Airport 
FRA: Frankfurt Airport

Basically, we use For Loops to iterate over something, whether that be numbers, arrays, dictionaries or specific data structure. There’s one last thing I want to show you and that is the () function.

Enumerations and For Loop

Now when we’re iterating through an array we just get the value. What if I want to get the index of every single item as well as the value? That’s where Enumerations come in handy.

var listOfAirports = ["LHR": "London Heathrow Airport", "FRA": "Frankfurt Airport", "JFK": "John F. Kennedy International Airport"] 

for (code, airport) in listOfAirports.enumerated() {
    print("\(code): \(airport)") 
}

// Prints
0: (key: "LHR", value: "London Heathrow Airport") 
1: (key: "JFK", value: "John F. Kennedy International Airport") 
2: (key: "FRA", value: "Frankfurt Airport")

Enumerations allow us to get both the index as well as the value, which is extremely useful when we want to find out the position of the object. That’s the main power of enumerations while using inside the For Loop.

Further Reading

The syntax for the For Loop is actually pretty simple. We are just repeating a piece of code for a certain number of times. However, I would still recommend you to create different loops on your own, to learn more about them. But for now lets quickly recap what we have just learned.

  • For loops are used to iterate over something for multiple times
  • We can use loops to iterate over a list of numbers, arrays or dictionaries
  • The stride function allows us to skip, increment or decrement our numbers
  • The enumerated() function gives us both the index and the value of our data

Happy Coding!