Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

#swift
communitycreator

Print the characters of a string using the forEach loop in Swift

Theodore Kelechukwu Onyejiaku

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)
}
Print characters of a string using the "forEach" loop in Swift

Code explanation

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

RELATED TAGS

#swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring