Swift For-In Loop Example

1. Introduction

Swift's for-in loop allows you to iterate over sequences, such as ranges of numbers, items in an array, or characters in a string. It provides a concise and readable way to run a set of statements for each item in a collection.

2. Source Code Example

// Looping over an array of integers
let numbers = [1, 2, 3, 4, 5]
for number in numbers {
    print("\(number) times 2 is \(number * 2)")

// Looping over a dictionary
let fruitColors = ["apple": "red", "banana": "yellow", "grape": "purple"]
for (fruit, color) in fruitColors {
    print("The color of \(fruit) is \(color)")

// Looping over a range
for i in 1...5 {
    print("The square of \(i) is \(i * i)")

// Looping over a string's characters
let greeting = "Hello"
for char in greeting {


1 times 2 is 2
2 times 2 is 4
3 times 2 is 6
4 times 2 is 8
5 times 2 is 10
The color of apple is red
The color of banana is yellow
The color of grape is purple
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25

3. Step By Step Explanation

1. Looping over Arrays: We create an array named numbers and then use a for-in loop to iterate over each integer. Inside the loop, we print the number, and it's double.

2. Looping over Dictionaries: The fruitColors dictionary associates fruits with their respective colors. With the for-in loop, we can destructure the dictionary items into (key, value) pairs. This allows us to access both the fruit's name and its color within the loop.

3. Looping over Ranges: Swift lets you create numerical ranges with ease. In this example, we iterate over the numbers 1 through 5, printing each number's square.

4. Looping over Strings: Strings are sequences of characters. This means we can use a for-in loop to iterate over each character in a string. We demonstrate this by looping through the greeting string and printing each character on a new line.

Swift's for-in loop is a powerful tool that offers a streamlined way to iterate over various collections and sequences. Its adaptability makes it an essential part of the language for tasks ranging from simple iterations to more complex data manipulation.