Waldo sessions now support scripting! – Learn more
App Development

Swift For Loop: Learn With Real-World Examples

Llamdo
Llamdo
Swift For Loop: Learn With Real-World Examples
October 26, 2021
10
min read

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:


for value in values {
   //Execute this code block
}

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


for i in 1...5 {
print(i)
}

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.


let name = "Tony"
for greeting in ["Hello, NAME!", "How you doing?", "Welcome to this application!", "How can I help you today, NAME?"]{
    let new_g = greeting.replacingOccurrences(of:"NAME", with: name, options: .literal, range:nil)
    print(new_g)
}

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:

Hello, Tony!

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.


let results = ["Maths":42, "English":47, "Science":42]
for (subject, score) in results {
print("Bob scored \(score) in \(subject)")
}

The output would look like this:

Swift for loop output example 1

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.


let results = ["Maths":42, "English":47, "Science":42]
var sum = 0
for (subject, score) in results {
sum = sum+score
print("Bob scored \(score) in \(subject)")
}
print("Bob scored a total of \(sum) in all subjects")

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:

Swift for loop output example 2

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.


let results = ["Bob": ["Maths":42, "English":47, "Science":42], "Alice": ["Maths":40, "English":37, "Science":48], "Tina": ["Maths":49, "English":49, "Science":50]]
for (name, result) in results
{
    for (subject, score) in result{
        print("\(name) scored \(score) in \(subject)")
    }
}

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:

Swift for loop output example 3

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.

Web scraping

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.

Web scraping and code

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:


//Importing required modules
import Foundation
import Kanna
//Get input from user
print("Enter number of results in a page:")
let res = readLine()
print("Enter number of pages:")
let page = readLine()
//Convert string input to integer to use in for loop and mathematical operations
let res_int:Int? = res.toInt()
let page_int:Int? = page.toInt()
start = 0
for i in 0...page_int-1{
print("***Results on page \(i+1)***)
//Get the web response
let url = URL(string:"https://www.google.com/search?q=waldo&start=\(start)&num=\(res)")!
let html = try String(contentsOf: url)
//Parse web response using Kanna
if document = Kanna.HTML(html: html, encoding: String.Encoding.utf8){
//Finding our class
for data in document.xpath("//div[@class='yuRUbf']"){
//Find the h3 and anchor tag
let title = document.at_xpath('a')
let link = title.at_xpath('h3')
//Printing data embedded in the above tags
print("Title: " + title?["href"] + ", Link: " + link?.text)
}
}
print(try document.title())
start = start+res_int
}

The output should be as follows:

Web scraping output

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.

To Conclude

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.

Automated E2E tests for your mobile app

Waldo provides the best-in-class runtime for all your mobile testing needs.
Get true E2E testing in minutes, not months.

Reproduce, capture, and share bugs fast!

Waldo Sessions helps mobile teams reproduce bugs, while compiling detailed bug reports in real time.