Lesson 27Collections

Iterating Collections

Looping Through Collections

Learn different ways to iterate over arrays, sets, and dictionaries to access each element!

Array Iteration

for item in array

Simple iteration

for (i, item) in array.enumerated()

With index

Dictionary Iteration

for (k, v) in dict

Key-value pairs

for k in dict.keys

Keys only

for v in dict.values

Values only

Special Iteration Methods

.forEach { }

Functional style iteration

.reversed()

Iterate in reverse order

Remember!

  • Sets and Dictionaries have no guaranteed order
  • Use .sorted() for ordered iteration
  • enumerated() gives you index + element
main.swift
// Iterating over Arrays
let fruits = ["Apple", "Banana", "Cherry"]

// Simple for-in loop
for fruit in fruits {
    print(fruit)
}

// With index using enumerated()
for (index, fruit) in fruits.enumerated() {
    print("\(index): \(fruit)")
}

// Iterating over Sets
let colors: Set = ["Red", "Green", "Blue"]

for color in colors {
    print(color)  // Order not guaranteed!
}

// Iterating over Dictionaries
let ages = ["Alice": 25, "Bob": 30, "Charlie": 35]

// Iterate key-value pairs
for (name, age) in ages {
    print("\(name) is \(age) years old")
}

// Iterate only keys
for name in ages.keys {
    print("Name: \(name)")
}

// Iterate only values
for age in ages.values {
    print("Age: \(age)")
}

// Sorted iteration (dictionaries are unordered)
for name in ages.keys.sorted() {
    print("\(name): \(ages[name]!)")
}

// Using forEach (functional style)
fruits.forEach { fruit in
    print("I love \(fruit)")
}

// With shorthand argument
fruits.forEach { print($0) }

// Reverse iteration
for fruit in fruits.reversed() {
    print(fruit)
}

// Iterate with stride
for i in stride(from: 0, to: 10, by: 2) {
    print(i)  // 0, 2, 4, 6, 8
}

Try It Yourself!

Create a dictionary of your favorite movies with ratings. Iterate through it and print only the movies with ratings above 8!