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
// CherryThe 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.74You 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
EasyWrite 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
// CherryThe 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.74You 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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input