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 string
let info = "Educative is the best!"
// use forEach function
// and print each character
info.forEach{
// print each character
print($0)
}

Code explanation

  • Line 2: We create a string.
  • Lines 6–9: We use the forEach function to print each character of the string.

Free Resources