Print the characters of a string using the forEach loop in Swift
Overview
Printing the characters of a string value in Swift using the forEach function or loop is easy. The forEach function iterates over the string and repeats an action—in this case, it prints the character—for each element of the string.
Syntax
string.forEach{
// print each character
print($0)
}
Parameter value
$0: This represents each character of the string as the loop executes.
Code example
// create a stringlet info = "Educative is the best!"// use forEach function// and print each characterinfo.forEach{// print each characterprint($0)}
Code explanation
- Line 2: We create a string.
- Lines 6–9: We use the
forEachfunction to print each character of the string.