Swift For Loop: Learn With Real-World Examples
When building applications, performance is one of the most critical parameters. With applications getting more complex day by day and their involvement in critical systems and processes, it’s very important to have your application provide results on time, which is where a good programming language can help. Swift is one such programming language that was built with performance in mind. Swift is a general-purpose, multiparadigm, compiled programming language developed by Apple Inc. and the open-source community. In this post, we’ll look into one of the foundational topics of programming: for loop in Swift.
For loops are a good way to reuse a block of your code with the same or different values. If I had to write a program to greet 10 people, I wouldn’t write a different code block to greet each person. I’d rather use a for loop. The applications of a for loop go a long way from here. In this post, we’ll go through different versions of for loops in Swift. But before that, let’s understand more about for loops.
Understanding For Loops
The syntax of a for loop in Swift looks like this:
And it has four main parts.
The first part is the for and in keywords used to indicate that this is a for loop. The value is the value that keeps getting updated with each iteration of the loop. And values are the collection of values that the for loop iterates through. Lastly, the code block is what the for loop executes on each iteration.
Now let’s convert the syntax into actual code and look at some Swift for loop examples.
Swift For Loop: Examples
You can use online compilers to run simple Swift programs. But if you’re building complex projects, you need to set up Swift on your system. We’ll start with a simple example of a for loop and move our way up.
The Basic For Loop
In this example, the for loop iterates through values from 1 to 5 and then prints one value in each iteration of the loop. The fun part here is that you don’t have to mention all values from 1 to 5 yourself. The 1…5 creates a range of values and the loop iterates through them.
For Loop on Array
Now let’s say you’re building a support bot for an application. The first thing to do is greet the user and then try to engage them. For a better experience, you want to make it look natural. So you want to send different messages. Let’s see how we can use a for loop here.
I’ve assigned the name “Tony” to the name variable. My collection has four statements, and I’m running a loop on them. Some of these have a placeholder for the username. The loop will update the value of greeting with the string in the collection. Inside the loop, I’m dynamically updating the name of the user by replacing the placeholder with the name. And then I print these statements.
The output of the above code is as follows:
For Loop on Dictionaries
In many cases, you’ll be dealing with key-value pairs. A dictionary is one such data structure. And it’s important to know how to run a loop on dictionaries.
Let’s say that the results of a user are stored in a database and assume you get the data as a dictionary from the database or after processing it. To keep it simple, I’ve initialized the dictionary in the code instead of querying to the database. Now, you need to print the score for each subject. Here’s how you’d do it.
The output would look like this:
In this example, I’m using the for loop to iterate through the key-value pairs of the dictionary. And while doing so, I’m also assigning the values of the key (subject) and the value (score) to two variables. Then I’m printing each of these.
We can also add code to calculate the total sum of scores a user has scored.
This code is a slightly modified version of the previous example. To calculate the sum of scores, I’ve created a var to hold the sum value. And in each iteration of the loop, I’m adding the score of each subject to the sum. And after the loop ends, I’m printing the sum total. The output is as follows:
To take it one step further, you can have nested dictionaries and nested loops.
Nested For Loops
For example, instead of the results of one student, you can have results for multiple students. And you’ll have to use nested for loops in such cases.
Here you have results for three students. The first loop iterates through the student name and their results. And the second loop iterates through the subject and the score. The output for this code is as follows:
These are some examples of how swift for loops can be used as a part of a bigger project. And now to get the feel of a complete project, let’s build a real-life example that uses Swift for loops.
Swift For Loop in Web Scraping
The problem statement is to scrape the title and link from Google Search results. Google Search has some parameters in the URL, and we’ll be using some of them in our example. Parameter q is used to define our search keyword. num is used to determine the number of results to display on a page. And start is used to declare from which result to start displaying results. For example, if my URL is https://www.google.com/search?q=swift+for+loop&num=2&start=4, then the webpage will display two results on the page starting from result four.
We’ll use this feature to scrape data from Google Search results based on user input denoting how many pages they need to get results from and how many results per page they want to see. I’ll be using the Kanna parser for this.
To scrape data, we need to know the structure of the page. You can just right-click on the title from the above result page and click on Inspect. You should be able to see the structure, which would show where our data is stored.
Based on the screenshot, we see that our data is present in the yuRUbf class. The title is under the h3 tag of this class, and the link is in the anchor tag. We’ll use this information to get data. The code is as follows:
The output should be as follows:
This is how simple for loops can play a major role in projects and applications.
Testing the Code
To be honest, I didn’t get the web scraping code completely right the first time I wrote it. I had to go back and forth to get it working for different values. And that means that the code can fail for multiple reasons. There are multiple things to test in this web scraping code, especially because user input is involved. Some of the things I would test are as follows:
- What happens if the user inputs a character or a word?
- What happens if a user inputs a huge value for the number of results on each page? Does Google support really huge numbers of results to be displayed on a single page?
- What happens if a user inputs a huge value for the number of pages? How would your code behave if this value is greater than the number of results?
- What if the URL is also taken as input from the user and that URL is not valid?
Maybe your application works for that one case that you were thinking about when you were building it. But does it work for other cases as well? So, depending on your code or application, you will have to test different things. You could go with testing platforms like Waldo to make testing easier.
I don’t remember one useful program I’ve written without loops. Different types of loops are meant for different scenarios, and in some cases, you might even have to combine them. For loops are a great way to reuse your code with slight changes to parts of the code. We went through some examples of for loops in Swift and how it can be used in a real-world project.
For loops look simple, but in some cases, they can be wearing. There was this one code I wrote in which for loops were the heart of the code. I had to use 10 to 15 nested for loops to get and process data. So, if you’re a beginner in Swift, I strongly recommend you to become very comfortable with for loops and nested for loops along with other foundational concepts. Check out our guides to SwiftUI buttons or SwiftUI lists. Looking for more tutorials and guides? Head over to our blog.
This post was written by Omkar Hiremath. Omkar is a cybersecurity team lead who is enthusiastic about cybersecurity, ethical hacking, and Python. He is keenly interested in bug bounty hunting and vulnerability analysis.