Menu
Coddy logo textTech

Iterating Over Strings P1

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

Just like arrays, strings in Swift are sequences of characters that you can iterate over. This makes it easy to process text one character at a time using the familiar for-in loop.

When you loop through a string, Swift gives you each character in order:

let word = "Hello"

for char in word {
    print(char)
}
// H
// e
// l
// l
// o

Each char in the loop is of type Character, not String. This distinction matters when you need to compare or manipulate individual characters.

You can use this technique to analyze text, such as counting specific characters:

let message = "banana"
var countA = 0

for char in message {
    if char == "a" {
        countA += 1
    }
}

print(countA)  // 3

Notice that when comparing a character, we use a single character in quotes like "a". Swift automatically treats this as a Character when comparing with another character.

challenge icon

Challenge

Easy
Write a function countVowels that takes text and returns the total count of vowels in the string.

Iterate through each character in the string and count how many are vowels (a, e, i, o, u). Count both lowercase and uppercase vowels.

Parameters:

  • text (String): The string to analyze

Returns: The total number of vowels found in the string (Int)

Example: If text is "Hello World", the function should return 3 (the vowels are e, o, o).

Cheat sheet

You can iterate over a string using a for-in loop to process each character:

let word = "Hello"

for char in word {
    print(char)
}
// H
// e
// l
// l
// o

Each char in the loop is of type Character, not String.

You can compare characters directly in conditions:

let message = "banana"
var countA = 0

for char in message {
    if char == "a" {
        countA += 1
    }
}

print(countA)  // 3

Try it yourself

func countVowels(text: String) -> 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