0
0
Swiftprogramming~5 mins

For-in loop with collections in Swift

Choose your learning style9 modes available
Introduction

A for-in loop helps you go through each item in a group one by one. It makes repeating actions easy and clear.

When you want to print every name in a list of friends.
When you need to add up all numbers in a collection.
When you want to check each item in a shopping cart.
When you want to change or use every element in an array or dictionary.
Syntax
Swift
for item in collection {
    // code to use item
}

item is a temporary name for each element as you loop.

collection can be an array, dictionary, set, or any group of items.

Examples
This prints each fruit name from the array.
Swift
let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
    print(fruit)
}
This adds all numbers in the scores array and prints the total.
Swift
let scores = [10, 20, 30]
var total = 0
for score in scores {
    total += score
}
print(total)
This goes through a dictionary and prints each name with their age.
Swift
let ages = ["Alice": 25, "Bob": 30]
for (name, age) in ages {
    print("\(name) is \(age) years old")
}
Sample Program

This program prints a sentence for each animal in the list.

Swift
let animals = ["Dog", "Cat", "Rabbit"]
for animal in animals {
    print("I love my \(animal)")
}
OutputSuccess
Important Notes

You can use any name instead of item to make your code clearer.

For dictionaries, use two names in parentheses to get both key and value.

For-in loops work with many types of collections, not just arrays.

Summary

For-in loops help you repeat actions for each item in a collection.

They work with arrays, dictionaries, sets, and more.

You write the loop with for item in collection and use the item inside the loop.