For Loops In Swift (How To)

Written by Reinder de Vries on August 24 2019 in App Development

For Loops In Swift (How To)

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 article 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.

Ready? Let’s go.

  1. The For Loop in Swift
  2. How To Loop Over Collections With For-In
  3. How To Loop Over Ranges With For-In
  4. How To Loop With While And Repeat-While
  5. Further Reading

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 variable 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 most 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 both ranges of numbers, collections and even strings. All with the same syntax!

In Swift, object types like arrays, dictionaries, ranges and strings are known as sequences or collections. Any sequence 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. 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.

Learn how to build iOS apps

Get started with iOS 13 and Swift 5

Sign up for my iOS development course, and learn how to build great iOS 13 apps with Swift 5 and Xcode 11.

How To 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.

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

You can also use index numbers and subscript syntax when working with a collection, like this:

for i in 0..<numbers.count {
    sum += numbers[i]
}

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.

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.

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..<points.count {
    let y = points[x]
    graph.drawPoint(x, y)
}

When you want to send a notification to every one of a user’s followers, for instance in a social media app, you’d use the for loop like this:

for uid in user.followers {
    sendNotification(withUID: uid)
}

You can loop over any collection that conforms to the Sequence or IteratorProtocol protocols.

How To 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..<items.count {
    // Do stuff···
}

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:

print((0···0).isEmpty) // Output: false
print((0..<0).isEmpty) // Output: true

How To 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. 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 always 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:

  • 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:
    while(condition == true) {
        // Repeat this
    }
    
  • 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:
    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 many 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!

Learn how to build iOS apps

Get started with iOS 13 and Swift 5

Sign up for my iOS development course, and learn how to build great iOS 13 apps with Swift 5 and Xcode 11.

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…

Want to learn more? Check out these resources:

Reinder de Vries

Reinder de Vries

Reinder de Vries is a professional iOS developer. He teaches app developers how to build their own apps at LearnAppMaking.com. Since 2009 he has developed a few dozen apps for iOS, worked for global brands and lead development at several startups. When he’s not coding, he enjoys strong espresso and traveling.