Swift for Loop Tutorial

by Dimitris Tasios
28 views

In this article, we will learn how to perform a for loop in Swift.

1. A Simple for Loop in Swift

Just like in other programming languages, we use a for loop in Swift to perform lines of code repeatedly and also to iterate through Collections. Let’s see a simple for loop in Swift that iterates through an array:

// MARK: A simple for loop, also known as a for-in loop
let languages = ["English", "Spanish", "Italian", "Greek"]

for language in languages {
    print("I speak \(language)")
}

The output is:

I speak English
I speak Spanish
I speak Italian
I speak Greek

As you can see, the syntax of a for loop in Swift is quite simple; we use a temporary variable of the same type as one element of the array, called language that acts as the current element of the array, which in turn we can use however we want. Notice that we would put any name for that temporary variable (it’s not checked semantically to much the name of the array, but this way it’s much more understandable to see what an element of the array represents).

2. Accessing The Indices of Elements

While the aforementioned kind of for loop is suitable if we only care about the elements of the array, we have no access to the indices of each element. In order to do that, we can use the built-in function enumareted() and alter the for loop as such:

print("Listing the languages I can speak: ")
for (languagePosition, language) in languages.enumerated() {
    print("\(languagePosition + 1). \(language)")
}

The output is:

Listing the languages I can speak: 
1. English
2. Spanish
3. Italian
4. Greek

By using the enumareted() method, the temporary variable after the for keyword becomes a tuple of type
(Int, typeOfArrayElement). The Int is the index while the typeOfArrayElement is the element of the array at the current index.

On the other side, if we only wanted the indices of the array and not its elements at all, we could use the indices property that each array has, like so:

for index in languages.indices {
    print(index)
}

The output is:

0
1
2
3

3. Using a for Loop in Swift With Ranges

Apart from looping through arrays, we can simply use a for loop in Swift with a numeric range. In this case, we do not need to have an array to loop through, we only perform repetitions starting from the beginning of the range, up to its end.

A numeric range is written as 1...5 or 3..<7. The former means “from 1 to 5, and 5 is included” while the latter means “from 3 to 7, and 7 is not included” which basically means “from 3 to 6”.

Let’s see how to write a for loop with numeric ranges:

for number in 10...15 {
    print(number)
}

print()

for number in 10..<15 {
    print(number)
}

The output is:

10
11
12
13
14
15

10
11
12
13
14

In this case, we wrote our range in place of the array. Because of the < symbol, the first range is a closed range while the second one is an open range. As a result, the number 15 is only printed on the closed range.

4. Not Needing neither the Element nor the Index

If we do not care about accessing either the element or the index during a for loop, we can place an underscore (_) after the for keyword.

for _ in 0...4 {
    print("Swift is fun.")
}

The output is:

Swift is fun.
Swift is fun.
Swift is fun.
Swift is fun.
Swift is fun.

5. Skipping a Few Repetitions Using Strides

In some cases, we might not want to perform an action on every single repetition, but rather, every few repetitions. For example, what if we wanted to repeat an action every 4 times? This can be achieved by using the stride(from:to:by) for open ranges and stride(from:through:by) for closed ranges.

for number in stride(from: 0, to: 30, by: 3) {
    print("Current number: \(number)")
}

print("\nDoing it again:\n")

for number in stride(from: 0, through: 30, by: 3) {
    print("Current number: \(number)")
}

The output is:

Current number: 0
Current number: 3
Current number: 6
Current number: 9
Current number: 12
Current number: 15
Current number: 18
Current number: 21
Current number: 24
Current number: 27

Doing it again:

Current number: 0
Current number: 3
Current number: 6
Current number: 9
Current number: 12
Current number: 15
Current number: 18
Current number: 21
Current number: 24
Current number: 27
Current number: 30

6. The where Clause

Often, we might only want to perform actions to some elements of an array, for instance, that satisfy a specific condition. One way to do that, would be to add an if statement, so if the statement is false the loop would continue to the next element.

But, there is already a built-in way to do this, by using a where clause, which will only execute the statements inside the for loop if its statement is true. Let’s see an example, one using the where clause and one using an if statement:

let numbers = [1, 57, 44, 21, 9, 34]

// example without where clause
print("Printing numbers < 30 without \"where\" clause:")
for number in numbers {
    if number < 30 {
        print(number)
    }
}

print()

// example with where clause
print("Printing numbers < 30 with \"where\" clause:")
for number in numbers where number < 30 {
    print(number)
}

The output is:

Printing numbers < 30 without "where" clause:
1
21
9

Printing numbers < 30 with "where" clause:
1
21
9

The outputs are the same in both cases, but by using the where clause, the code is easier to read and understand. We also save indenting by one tab space, which is always good.

7. Other Collections

The aforementioned syntaxes and methods are also available to other collections, not just arrays. Actually, all custom classes and custom collection types can be used in a for loop in Swift, as long as they conform to the Sequence protocol.

Let’s see an example for Dictionaries, Strings, and Enums.

7.1 for Loop in Swift with Dictionaries

First of all, remember that a Dictionary is an unordered collection type whose elements have a key and a value. The key is used to access the value of the element, just like the index is used to access the element of an array.

We can iterate through Dictionaries just like Arrays, by either focusing on the index, the element, both, or none (we will focus on the more common case, of accessing both key and value). Take a look at our delicious example:

let pizzas = ["Marinara": 2, "Margherita": 3, "Capriciosa": 3.4, "Diavola": 3.6, "Quattro Formaggi": 5.5]

print("Our pizza menu is:")
for (pizza, price) in pizzas {
    print("\(pizza) costs \(price)€")
}

The output is:

Capriciosa costs 3.4€
Quattro Formaggi costs 5.5€
Diavola costs 3.6€
Marinara costs 2.0€
Margherita costs 3.0€

As you can see, the elements of a dictionary are accessed randomly, so every time we run the for loop, the pizzas would be printed in a different order each time.

7.2 for Loop in Swift with Strings

In Swift, Strings are an array of characters, so each character can be accessed just like an array. In the following example, we only print the punctuation characters of our phrase:

let longPhrase = "This is a long phrase for this example, don't you think?"
for character in longPhrase where character.isPunctuation {
    print(character)
}

The output is:

,
'
?

7.3 for Loop in Swift with Enums

By default, an Enum cannot be iterated in a for loop. In order to do that, we have to conform it to the CaseIterable protocol and use its allCases property.

enum ColorsEnum: CaseIterable {
    case red
    case green
    case purple
    case blue
    case yellow
}

for color in ColorsEnum.allCases {
    print(color)
}

The output is:

red
green
purple
blue
yellow

8. Conclusion

By now, you should be able to know and effectively use a for loop in Swift. You can find the source code (Playground) on our GitHub page.

9. Sources

[1]: Control Flow – Swift.org

[2]: Sequence – Apple

[3]: CaseIterable – Apple

Related Posts