How to iterate over characters in a string in Swift

You can iterate (loop) over a string’s characters using a regular for loop by treating it as an array:

let str = "Foundation Swift String”

for char in str {
    print("character = \(char)")
}

The above code prints out each character in a new line.

Alternatively, you can use the forEach(_:) method on a string, which calls a given closure on each character of the string:

str.forEach { char in
    print("character = \(char)")
}

Iterate over characters in a string with access to their index

This is where enumerated() instance method of String comes in handy. It returns a sequence of pairs, giving you access to each character and its index.

let str = "Foundation Swift String"

for (index, char) in str.enumerated() {
    print("index = \(index), character = \(char)")
}

The output for first iteration of this loop will look like this:

index = 0, character = F

Related tutorials: