Menu
Coddy logo textTech

Iterating Over Elements

Part of the Fundamentals section of Coddy's Swift journey — lesson 69 of 86.

Now that you know how to create and modify arrays, let's explore how to process each element one by one. The for-in loop makes this incredibly straightforward.

When you use a for-in loop with an array, Swift automatically gives you each element in order:

let fruits = ["Apple", "Banana", "Cherry"]

for fruit in fruits {
    print(fruit)
}
// Apple
// Banana
// Cherry

The variable fruit takes on each value from the array during each iteration. You can name this variable anything that makes sense for your data.

This pattern is perfect for performing operations on every element, like calculating a total:

let prices = [9.99, 14.50, 3.25]
var total = 0.0

for price in prices {
    total += price
}

print(total)  // 27.74

You can also use the loop to build new arrays based on existing ones:

let numbers = [1, 2, 3, 4]
var doubled = [Int]()

for number in numbers {
    doubled.append(number * 2)
}

print(doubled)  // [2, 4, 6, 8]

Iterating over arrays is one of the most common operations in programming, so mastering this pattern will serve you well.

challenge icon

Challenge

Easy
Write a function countPositives that takes numbers and returns the count of positive numbers in the array.

Use a for-in loop to iterate through each element and count how many are greater than zero.

Parameters:

  • numbers ([Int]): An array of integers

Returns: The count of positive numbers (greater than 0) in the array (Int)

Example: If numbers is [-3, 5, 0, 8, -1, 12], the function should return 3 (the positive numbers are 5, 8, and 12).

Cheat sheet

Use a for-in loop to iterate through each element of an array:

let fruits = ["Apple", "Banana", "Cherry"]

for fruit in fruits {
    print(fruit)
}
// Apple
// Banana
// Cherry

The loop variable (fruit in this example) takes on each value from the array during each iteration.

You can use for-in loops to calculate totals:

let prices = [9.99, 14.50, 3.25]
var total = 0.0

for price in prices {
    total += price
}

print(total)  // 27.74

You can also build new arrays by iterating over existing ones:

let numbers = [1, 2, 3, 4]
var doubled = [Int]()

for number in numbers {
    doubled.append(number * 2)
}

print(doubled)  // [2, 4, 6, 8]

Try it yourself

func countPositives(numbers: [Int]) -> Int {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals