The Enumerated Method
Part of the Fundamentals section of Coddy's Swift journey — lesson 70 of 86.
Sometimes when iterating over an array, you need to know not just the element, but also its position. While you could manually track the index with a counter variable, Swift provides a cleaner solution: the enumerated() method.
When you call enumerated() on an array, it returns a sequence of tuples, where each tuple contains the index and the element:
let colors = ["Red", "Green", "Blue"]
for (index, color) in colors.enumerated() {
print("\(index): \(color)")
}
// 0: Red
// 1: Green
// 2: BlueNotice how we decompose each tuple directly in the loop using (index, color). This gives us access to both values without any extra code.
This is particularly useful when you need to display numbered lists or perform operations that depend on an element's position:
let tasks = ["Wake up", "Exercise", "Eat breakfast"]
for (index, task) in tasks.enumerated() {
print("Task \(index + 1): \(task)")
}
// Task 1: Wake up
// Task 2: Exercise
// Task 3: Eat breakfastThe enumerated() method keeps your code clean and readable compared to manually managing a separate counter variable.
Challenge
EasyWrite a function formatWithPositions that takes items and returns a formatted string showing each item with its position number.
Use the enumerated() method to iterate through the array and build a string where each item is prefixed with its 1-based position number.
Logic:
- Iterate through the array using
enumerated() - For each element, create a string in the format
"position. item"(using 1-based numbering) - Join all formatted strings with a newline character (
\n)
Parameters:
items([String]): An array of strings to format
Returns: A single string with each item on its own line, prefixed with its position number (String). Format: "1. item1\n2. item2\n3. item3"
Example: If items is ["Apple", "Banana", "Cherry"], the function should return:
"1. Apple\n2. Banana\n3. Cherry"Note: If the array is empty, return an empty string "".
Cheat sheet
The enumerated() method returns a sequence of tuples containing both the index and element of an array:
let colors = ["Red", "Green", "Blue"]
for (index, color) in colors.enumerated() {
print("\(index): \(color)")
}
// 0: Red
// 1: Green
// 2: BlueEach tuple is decomposed directly in the loop using (index, element) syntax, providing access to both the position and value.
This is useful for creating numbered lists by adding 1 to the zero-based index:
let tasks = ["Wake up", "Exercise", "Eat breakfast"]
for (index, task) in tasks.enumerated() {
print("Task \(index + 1): \(task)")
}
// Task 1: Wake up
// Task 2: Exercise
// Task 3: Eat breakfastTry it yourself
func formatWithPositions(items: [String]) -> String {
// 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