Swift for-in Loop Tutorial 🎯

beginner
12 min

Swift for-in Loop Tutorial 🎯

Welcome to the Swift for-in Loop tutorial! In this comprehensive guide, we'll explore the for-in loop, a powerful tool for iterating through collections in Swift. By the end of this lesson, you'll be able to write your own for-in loops to handle real-world programming challenges. Let's dive in!

What is a for-in Loop? 📝

The for-in loop is used to iterate over a collection, such as arrays, dictionaries, or strings, in Swift. It's a handy way to process each item in a collection one by one, making it an essential tool for working with collections.

Why use a for-in Loop? 💡

Using a for-in loop is beneficial when you need to perform an action multiple times, and each iteration requires access to a specific element in a collection. It simplifies the process of iterating over collections and is more readable than using traditional while or for loops.

The Anatomy of a for-in Loop 📝

A basic for-in loop consists of the following components:

swift
for item in collection { // Code to be executed for each item }
  • item: A variable that holds the current item from the collection.
  • in: A keyword separating the variable and the collection.
  • collection: The collection being iterated over.

Practical Example 🎯

Let's create a simple example where we iterate over an array of fruits and print each fruit.

swift
let fruits = ["Apple", "Banana", "Cherry", "Date"] for fruit in fruits { print(fruit) }

When you run this code, it will output:

Apple Banana Cherry Date

Looping through Dictionaries 📝

You can also use a for-in loop to iterate through dictionaries. Each iteration will return a (key, value) tuple, allowing you to access both the key and value of the current item in the dictionary.

swift
let person = ["name": "John", "age": 30, "city": "New York"] for (key, value) in person { print("\(key): \(value)") }

Output:

name: John age: 30 city: New York

Nested for-in Loops 📝

Nested for-in loops are useful when you need to iterate over multiple collections simultaneously or perform multiple iterations within a single loop.

swift
let numbers = [1, 2, 3, 4, 5] let letters = ["A", "B", "C", "D", "E"] for i in 0..<numbers.count { for j in 0..<letters.count { print("\(letters[j])\(numbers[i])") } }

Output:

A1 B2 C3 D4 E5

Skipping Items with the break and continue Keywords 📝

The break and continue keywords can be used within a for-in loop to alter its behavior.

  • break: Exits the loop immediately when the break statement is encountered.
  • continue: Skips the current iteration and moves on to the next one.

Here's an example that demonstrates the use of break and continue:

swift
let numbers = [1, 2, 3, 4, 5] for number in numbers { if number == 3 { print("Skipping 3") continue } if number == 5 { print("Breaking the loop at 5") break } print(number) }

Output:

1 2 Skipping 3 4

Quiz 💡

Quick Quiz
Question 1 of 1

What is the output of the following code?