DEV Community

Cover image for For Loop in Swift
Swift Anytime
Swift Anytime

Posted on • Originally published at swiftanytime.com

For Loop in Swift

In this guide, you will learn about For Loop in Swift. We will see many examples of how to use for-loop over collections and ranges.

Looping means repeating an action over and over again. In Swift, there are some control flow statements that are used to control the execution flow of code. Some of them (like for-loop and repeat-while) are used to perform repeating tasks.

For-Loops are used to repeat a task following a termination condition.

For loop Usage

For loop is a well-known statement for repeating a task. It's also known as the for-in loop.

For loop with array

Let's see how to iterate elements of an array:

let countries = ["India", "Australia", "Canada", "Denmark", "France"]

for countryName in countries {
    print(countryName)
}
Enter fullscreen mode Exit fullscreen mode

In the above example, you can see how to iterate array elements using a for loop. We are printing each element one by one.

The for loop syntax contains two placeholder, first we declare a constant with a certain name (countryName) after for then we specify from which collection (countries) the value for the constant iterate over.

Scope of the for loop

let numbers = [10, 32, 9, 56, 70]

for number in numbers {
    var sum = 0
    sum += number
}

print("sum is: \(sum)")
Enter fullscreen mode Exit fullscreen mode

Once you build this code, you will get an error like the below:

Cannot find 'sum' in scope
Enter fullscreen mode Exit fullscreen mode

As you can see clearly in the error message, the sum variable is not accessible outside the loop block, this cause the constant declared in for loop are only available inside the scope of the loop closure

For loop with dictionary

Let's see how to iterate elements of a dictionary:

let profileDictionary: [String: Any] = ["name": "Katrina Martin",
                                        "age": 21,
                                        "address": "NYC",
                                        "qualification": "MBA"]

for element in profileDictionary {
    print(element)
}

/*
Output:
(key: "name", value: "Katrina Martin")
(key: "address", value: "NYC")
(key: "age", value: 21)
(key: "qualification", value: "MBA")
*/
Enter fullscreen mode Exit fullscreen mode

In the above example, you can see the output is in the form of a tuple of key-value pairing. When you iterate a dictionary through a loop, it always returns a pair of key-value.

If you want to access key or value individually, you can access them using tuple's parameterised syntax like below:

print(element.key, element.value)
Enter fullscreen mode Exit fullscreen mode

Another way you can use to iterate elements of a dictionary:

for (key, value) in profileDictionary {
   print(key, value)
}
Enter fullscreen mode Exit fullscreen mode

For loop with range

Let's see how to for-loop with the range operator:

With closed range:

for element in (1...5) {
    print(element)
}

/*
Output:
1
2
3
4
5
*/
Enter fullscreen mode Exit fullscreen mode

With half-open range:

for element in (1..<5) {
    print(element)
}

/*
Output:
1
2
3
4
*/
Enter fullscreen mode Exit fullscreen mode

In the above examples, you can see how for-loop works with closed range and half-open range.

Iterate a string

We know that a string is a collection of characters so we can iterate each character of a string like below:

let string = "Swift Anytime"

for character in string {
    print(character)
}

/*
// Output:
S
w
i
f
t

A
n
y
t
i
m
e
*/
Enter fullscreen mode Exit fullscreen mode

Where Clause in For-Loop

With for-loop, you can filter the element using where clause based on a condition. You can say it is an alternative to replace if statement in the for loop.

First, let's understand an example when we can use where clause with for loop.

let numbers = [10, 32, 9, 56, 70]

for number in numbers {
    if number % 2 == 0 {
        print("Number \(number) is even.")
    }
}

/*
Output:
Number 10 is even.
Number 32 is even.
Number 56 is even.
Number 70 is even.
*/
Enter fullscreen mode Exit fullscreen mode

In the above example, we are using a single if statement to check the number is even or not.

Now let's use the where clause to do the same thing:

for number in numbers where number % 2 == 0 {
    print("Number \(number) is even.")
}

/*
Output:
Number 10 is even.
Number 32 is even.
Number 56 is even.
Number 70 is even.
*/
Enter fullscreen mode Exit fullscreen mode

Now, you can differentiate that, where clause method is more suitable to filter out the elements based on a condition.

What next?

In this article, you learned about for loop, and how it works with collections, strings. Now, you can do some practice by exploring some more usage of for loop. We encourage you to read more related articles like, Dictionaries in Swift, Arrays in Swift, till then, have a great time ahead.

Eat. Sleep. Swift Anytime. Repeat.

Top comments (0)