How To: For Loops In Swift

Written by: Reinder de Vries, October 4 2017, in App Development

How To: For Loops In Swift

Loops are a fundamental concept of programming. You can repeat stuff with loops, saving you time, and making your code more concise. Here’s how you use loops in Swift.

In this article you’ll learn how to use the for-in loop, with both collections and ranges, and what other approaches are useful to iterate over stuff. Practical app developers must master the for-loop, it’s a super useful tool in any developer’s toolkit.

Ready? Let’s go.

  1. Using the For-In Loop in Swift
  2. Looping Over Collections
  3. Looping Over Ranges
  4. Other Approaches to Looping Over Stuff
  5. Further Reading

Using the For-In 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 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 language, the for-in loop is called for-each. Typical 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. 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-in loop.

Grab My Free iOS Development Course

Get complementary access to my course, Zero to App Store, and learn how you can build a real-time chat app with Firebase and Swift!

Yes, Send Me The Free Course!

Looping Over Collections

Let’s not stick to theory here! What are good scenarios for using for-loops to loop 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:

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

Interestingly, 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]
}

In practical app development, for-in loops and collections come in handy in scenarios like the following.

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, loop over it, 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.

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-in loop like this:

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

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

Looping Over Ranges

You’ve already looked at ranges for a bit, but let’s dive deeper. It’s easy to imagine using the for-in 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)
}

// Output: 1 2 3 4 5

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

Other Approaches to Looping Over Stuff

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 loops to, 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 stuff. 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!

Grab My Free iOS Development Course

Get complementary access to my course, Zero to App Store, and learn how you can build a real-time chat app with Firebase and Swift!

Yes, Send Me The Free Course!

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…

Got a question? Let me know in the comments!

Want to learn more? Check out these resources:

Enjoyed this article? Please share it!

Written By: Reinder de Vries

Reinder de Vries is an indie app developer who teaches aspiring app developers and marketers how to build their own apps at LearnAppMaking.com. Since 2009 he has developed over 50 apps for iOS, Android and the web, and his code is used by millions of users all over the globe. When Reinder isn't building apps, he enjoys strong espresso and traveling.

Grab My Free iOS Development Course

Get complementary access to my course, Zero to App Store, and learn how you can build a real-time chat app with Firebase and Swift!

Yes, Send Me The Free Course!

Comments & Thoughts