Menu
Coddy logo textTech

Iterating Over Strings P2

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

Just like we used enumerated() with arrays to get both the index and element, we can do the same with strings. This is useful when you need to know the position of each character while iterating.

let word = "Swift"

for (index, char) in word.enumerated() {
    print("\(index): \(char)")
}
// 0: S
// 1: w
// 2: i
// 3: f
// 4: t

This technique is helpful when building new strings based on character positions. For example, you might want to keep only characters at even indices:

let text = "abcdef"
var result = ""

for (index, char) in text.enumerated() {
    if index % 2 == 0 {
        result += String(char)
    }
}

print(result)  // ace

Notice that we convert char to a String using String(char) before appending it. This is necessary because result is a String, and you cannot directly append a Character to it using the += operator.

challenge icon

Challenge

Easy
Write a function extractOddIndexChars that takes text and returns a new string containing only the characters at odd indices.

Use enumerated() to iterate through the string and build a result containing characters where the index is odd (1, 3, 5, etc.).

Parameters:

  • text (String): The input string to process

Returns: A string containing only the characters at odd indices (String)

Example: If text is "abcdefg", the function should return "bdf" (characters at indices 1, 3, and 5).

Cheat sheet

Use enumerated() with strings to get both the index and character while iterating:

let word = "Swift"

for (index, char) in word.enumerated() {
    print("\(index): \(char)")
}
// 0: S
// 1: w
// 2: i
// 3: f
// 4: t

When building strings based on character positions, convert Character to String before appending:

let text = "abcdef"
var result = ""

for (index, char) in text.enumerated() {
    if index % 2 == 0 {
        result += String(char)
    }
}

print(result)  // ace

Use String(char) to convert a Character to a String when appending with +=.

Try it yourself

func extractOddIndexChars(text: String) -> String {
    // 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