Back to blog

For Loops in Swift (How To)


Abhinav Girdhar
By Abhinav Girdhar | Last Updated on December 10th, 2023 6:36 am | 5-min read

A for loop is a fundamental concept of programming. You can repeat code with a for loop, and make your code more expressive and elegant. You use for-in, while and repeat-while to loop in Swift.

In this tutorial you’ll learn how to use the for-in loop, with collections and ranges, and how to use other approaches like while and repeat-while.

The for loop in Swift is a super useful tool in any developer’s toolkit, so it’s a must to master as a practical iOS developer.

Describe your app idea
and AI will build your App

Iterating with The For Loop in Swift

The syntax for loops in Swift is surprisingly simple. Here’s an example:

for item in items {
// Do this
}

A for loop in Swift always has the for and in keywords. The for loop then takes a sequence, items in the example above, and loops over the sequence one-by-one. With the syntax above, every item is available as the constant item within the loop. The code that’s repeated is within the squiggly brackets { }.

You can read the above example code as:

For every “item” in “items”, execute this code.

In many programming languages, the for in loop is called for-each. Typical for loop syntax in other languages uses this format: for(i = 0; i < n; i++) { ... }. Swift is different, because its for-in syntax can be used to loop over ranges, sequences, iterators, collections and even strings. All with the same syntax! In Swift, object types like arrays, dictionaries and sets are known as collections. Any collection can be iterated with a for-in loop. OK, let’s look at another example: for n in 1...5 { print(n) } // Output: 1 2 3 4 5 The example above uses the closed range operator ... to create a range that goes from 1 to 5, including 5. Like this, you can repeat a particular instruction, like print(), a limited number of times. In the next sections you’ll look at some practical uses of the for loop. It’s easy to accidentally create a loop that repeats one too few or too many times. This is called an off by one error.

Loop over Collections with For-In

Let’s not stick to theory here! What are good scenarios for using for loops to iterate over collections?

As you know, arrays and dictionaries are collections. In Swift, you can also define your own collections, like the Results collection from the Realm database framework.

Arrays

Let’s look at an example:

let names = [“Arthur”, “Zaphod”, “Trillian”, “Ford”, “Marvin”]

for name in names {
print(name)
}

The above example will print out all the strings in the array, one by one. The variable names has no explicit type, but it’s inferred to be an array of strings: [String]. Therefore, the variable type of name must be String.

Here’s another example:

let numbers = [1, 2, 3, 4, 5, 6]
var sum = 0

for i in numbers {
sum += i
}

print(sum)

What if you want to create a function that returns the sum of any array of integer numbers? You’d code it like this, with a for loop:

func sum(_ numbers:[Int]) -> Int
{
var sum = 0

for n in numbers {
sum += n
}

return sum
}

let result = sum([23, 11, 9, 3, 24, 77])
print(result) // Output: 147

What’s interesting is that you also can use a collection’s index to reference a particular item. Instead of for item in items, you do this:

for i in 0..

Dictionaries

How can you iterate over a dictionary? Here’s how:

let scores = [“Bob”: 42, “Alice”: 99, “Jane”: 13]

for (name, score) in scores
{
print(“\(name)’s score is \(score)”)
}

In the above code, we’ve defined a scores dictionary with names and scores. The type of scores is [String: Int], so the dictionary has String keys and Int values.

In the for in loop, we’re deconstructing the key-value pair into a tuple (name, score). The value name corresponds to the dictionary item’s key, and the value score corresponds to the dictionary item’s value. You’re turning the tuple into 2 separate constants.

What if you’ve got an array, and you still want to access the index for each item in the array? You can’t use the for name in names syntax we’ve used before! Fortunately, arrays have a helpful enumerated() function. Here’s how you use it:

let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]

for (n, prime) in primes.enumerated()
{
print(“\(n) = \(prime)”)
}

In the above code, we’ve defined an array of integers called primes. In the for loop, we’re deconstructing the index and the value of the array item into the tuple (n, prime). We’re using the enumerated() function on primes to do that. This function will return an array with tuples, consisting of indices and values. That’s exactly what we need!

Grabbing the index of an array value like this is exceptionally helpful if you want to know “where” in the array you are. You can use the index to refer back to the same array item, later on.

Use Cases

In practical app development, for loops and collections are useful in the following scenarios.

When you want to apply the same style to several UI elements of the same type, like buttons. You simply put the buttons in the array, iterate the collection with a for loop, and set the styles to each individual button in the for loop.

Like this:

let buttons = [loginButton, signupButton, facebookButton]

for button in buttons {
button.backgroundColor = UIColor.red
button.layer.cornerRadius = 5.0
}

When you want to loop over a data set, for instance to plot a set of numbers on a line graph. You’d draw the line graph by iterating every data point on it, with a for loop.

let points = [0.1, 0.2, 0.3, 0.5, 0.7, 0.8]

for x in 0..

Loop over Ranges with For-In

You’ve already looked at ranges for a bit, but let’s dive deeper. It’s easy to imagine using the for loop to iterate collections, but iterating over ranges is just as interesting.

Here’s that code example with the closed range operator again:

for n in 1…5 {
print(n)
}

The closed range operator … creates a struct of type ClosedRange. As you’ve seen in the previous example, the closed range takes two parameters: the lower bound (first) and the upper bound (last). It then produces a range between those numbers, including the last one.

Interestingly, you can also create ranges with text characters! Like this:

let xyz = “x”…”z”
print(xyz.contains(“y”))
// Output: true

The ClosedRange struct has a cousin called Range, with the half-open range operator ..<. It produces a range between the upper and lower bound, but then without including the upper bound itself. Like this: for i in 0..<5 { print(i) } // Output: 0 1 2 3 4 You’ll discover that the half-open range operator comes in handy in programming, because you’re often dealing with ranges that run from 0 to, for instance, the end of an array. The index of the last item of an array is always equal to the size of the array minus one. If you want a range that runs from 0 to the end of the array, you logically get this: for i in 0..Fun Fact: Closed ranges can’t be empty, because they’ll always include a “distance” between the lower and upper bound – even if it’s 0. Half-open ranges can be empty, because the upper bound isn’t included in the range. Try this:
(0…0).isEmpty // false
(0..<0).isEmpty // true

Loop with While and Repeat-While

Iterating over a set of data or instructions is a crucial concept in programming for two reasons:

  • Computation and automation is nothing more than repeating a set of instructions. If you find yourself using a particular piece of code multiple times, with similar outcomes, you might want to consider using a loop.
  • The Don’t-Repeat-Yourself (DRY) principle states that… you shouldn’t repeat yourself (see what I did there?). This applies to for loops too, so if you’re doing something three times, when you could do it once and repeat it three times, it’s often smarter to create a loop.

The for-in loop isn’t the only kind of loop syntax that Swift has. There’s a couple more:

  1. The while loop repeats code until a condition becomes false. It’s most useful when you want to repeat something, but you don’t know how many times. The condition is always evaluated at the start of the loop. Like this:
  2. while(condition == true) {
    // Repeat this
    }

  3. The repeat-while loops is exactly the same as the while loop, except that it evaluates the condition at the end of the loop. It’ll always run at least once! Like this:
  4. repeat {
    // Do this
    } while(condition == true)

The for-in, while and repeat-while statements are the most basic approaches to repeat code. In Swift, and in the iOS SDK, you’ll find more concepts of iteration. It’s always good to consider these other options, otherwise you might find yourself writing inefficient and overly extensive code.

A few examples:

  • If you want to manipulate arrays, for instance to apply a function to each of the array elements, or to reduce the array to one result (like “sum”), then you should use the filter(), map() and reduce() higher-order functions.
  • If you want to show cells in a table view, you should use the default UITableView implementations to load the cell, display and reuse it. Even though this doesn’t literally involve a loop, it does repeat a set of instructions multiple times.
  • If you write a function that takes the output of itself as input for a consequent iteration, you should use recursion instead of a loop.

And that’s all there is to it!

Further Reading

So, now you know how to write for-in loops in Swift, and what they’re best used for. You know what they say – a lazy programmer is a good programmer! Never code things twice if you can use a loop instead…


Abhinav Girdhar

Founder and CEO of Appy Pie

App Builder

Most Popular Posts