Mastering Loops in Swift: A Comprehensive Guide

KD Knowledge Diet
4 min readApr 20, 2024

Swift, a versatile and powerful programming language, offers a variety of built-in ways to iterate over collections like arrays, sets, and dictionaries. Understanding these loop constructs is essential for efficiently handling data in your Swift programs. In this guide, we’ll explore different loop types and techniques, enabling you to wield the full power of Swift’s looping capabilities.

The Basics: for Loops

The most fundamental loop in Swift is the `for` loop. It allows you to execute a block of code for each element within a collection. Let’s start with a simple example where we have an array of names and want to print each name:

let names = ["John", "Emma", "Robert", "Julia"]
for name in names {
print(name)
}

Alternatively, you can achieve the same result by using the `forEach` method on an array, which takes a closure to be executed for each element:

names.forEach { name in
print(name)
}

One significant difference between a `for` loop and `forEach` is that the latter doesn’t allow you to break out of the iteration prematurely based on a condition. For instance, using a `for` loop, you can exit the loop when a specific condition is met:

for name in names {
if name == "Robert" {
break
}
print(name) // This will only print "John" and "Emma"
}

Advanced for Loop Techniques

Swift’s `for` loop provides various techniques for more advanced iterations. For example, if you need to access both the index and element during the loop, you can use a range-based `for` loop:

for index in 0..<names.count {
print(index, names[index])
}

Alternatively, you can loop through an array’s indices directly using the `indices` property:

for index in names.indices {
print(index, names[index])
}

Another useful method is `enumerated()`, which converts an array into a sequence of tuples containing the index and its associated element:

for (index, name) in names.enumerated() {
print(index, name)
}

Working with while Loops

Swift also supports `while` loops, which repeatedly execute a block of code as long as a given boolean condition remains true. Here’s an example of a `while` loop that appends names from an array to a string as long as the string’s length is less than 8 characters:

let names = ["John", "Emma", "Robert", "Julia"]
var index = 0
var string = ""
while string.count < 8 {
string.append(names[index])
index += 1
}
print(string) // "JohnEmma"

An alternative way to construct a `while` loop is by using a `repeat` block. This block is repeatedly executed as long as the `while` condition evaluates to true:

let names = ["John", "Emma", "Robert", "Julia"]
var index = 0
var string = ""
repeat {
string.append(names[index])
index += 1
} while string.count < 8
print(string) // "JohnEmma"

The key difference between `repeat` and a stand-alone `while` loop is that the `repeat` block is guaranteed to run at least once, even if the initial `while` condition is false.

However, when using `while` loops, it’s crucial to ensure that each loop eventually terminates. You can do this either by manually using `break` or by designing your boolean condition to become false when the loop should stop. For example, you can add an additional condition to check the index against the array’s count:

while string.count < 8, index < names.count {
string.append(names[index])
index += 1
}

Alternatively, you can include the index-check within the loop using a `guard` statement:

while string.count < 8 {
guard index < names.count else {
break
}
string.append(names[index])
index += 1
}

Simplifying with Swift’s for…in Filter

Swift provides a more concise way to handle simple loops with the `for…in` filter. For example, if you want to iterate through an array while a specific condition holds, you can use the `where` keyword:

let names = ["John", "Emma", "Robert", "Julia"]
var string = ""
for name in names where string.count < 8 {
string.append(name)
}
print(string) // "JohnEmma"

While both `for` and `for…in` are valid, the latter often results in more readable and concise code.

Diving into Dictionaries

Swift’s dictionaries can also be iterated over using similar techniques. However, when looping through dictionaries, you work with key-value pairs. Here’s how to iterate through a dictionary where each key is a category and its value is an array of names:

let namesByCategory = [
"friends": ["John", "Emma"],
"family": ["Robert", "Julia"]
]
for (category, names) in namesByCategory {
print(category, names)
}

Sometimes, you may only need the keys or values from a dictionary. Swift provides dedicated methods for this purpose:

for category in namesByCategory.keys {
print(category)
}
for names in namesByCategory.values {
print(names)
}

If you need to control the order of iteration, especially with dictionaries, which are unordered collections, you can sort the keys and iterate in a predictable manner:

for category in namesByCategory.keys.sorted() {
print(category)
}

Conclusion

Mastering loops in Swift is essential for effective programming. Swift offers a variety of loop constructs, each with its own strengths and use cases. Whether you’re working with arrays, sets, dictionaries, or other collections, Swift provides the tools you need to iterate through your data efficiently and elegantly.

As you become more comfortable with Swift’s loop constructs, you’ll be able to choose the most appropriate one for each situation, making your code more readable and maintainable. Swift’s flexibility and expressive syntax make it a joy to work with loops and collections, enabling you to write efficient and clean code.

If you have any questions, comments, or feedback, feel free to reach out via Twitter or email. Happy coding!

Thanks for reading!

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!