> For the complete documentation index, see [llms.txt](https://ios-course.cornellappdev.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ios-course.cornellappdev.com/resources/swift-foundations/arrays/iteration-and-enumeration.md).

# Iteration and Enumeration

Iteration over arrays is quite straightforward because an array is already a sequence. Thus, we can directly iterate over arrays:

```swift
for <identifier> in <array> {
    <instructions to execute>
}
```

Sometimes though, you may want to iterate over the element as well as their respective locations in the array. This is achievable in two ways. The naive method would be to iterate in a range from 0 to the length you are iterating to. This would allow you to bind the index to your identifier and then you can just get the element at the corresponding location through subscripting. The better method would be to use enumeration. All arrays have an `enumerated()` method, which returns an `EnumeratedSequence`. Forgetting the jargon (I'm sure there's a lot of excessive type aliasing going on) `enumerated` converts your array into another array of tuples containing the indices and elements respectively. Basically, think of `enumerated` as having the type: `[Element] -> [(Int, Element)]`.&#x20;

```swift
let myStrings = ["a", "b", "c"]
for (index, i) in myStrings.enumerated() {
    print(index, i)
}
// 0 a
// 1 b
// 2 c
```

You'll notice I use a funky identifier there (index, i). Tuples allow us to assign multiple values at once. The nth element of the tuple is assigned to the nth element of the tuple of identifiers.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ios-course.cornellappdev.com/resources/swift-foundations/arrays/iteration-and-enumeration.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
