What are escape sequence characters in Swift?

Overview

Escape sequence characters are characters that do not represent themselves when used in a string. Rather, they tell the computer to perform a certain function or command. All escape sequences begin with an escape character.

Some escape sequence characters along with their description are given below:

  • \n: This is a newline character. It the computer to move to the next line.
  • \t: This is a tab. It tells the computer to leave a tab.
  • \r: This is the carriage return. It tells the computer to move the cursor to the starting of the line.
  • \' or \": A single quote or double quote. This tells the computer to wrap a string or character with quotation marks.
  • \\: A backward slash. This tells the computer to add a backward slash to a string.

Return value

The value these escape sequences return is a function telling the computer what to do.

Example

// use escape sequences in strings
print("Welcome to\nEdpresso!"); // a new line
print("Welcome to\tEdpresso!"); // a tab
print("Welcome to\rEdpresso!"); // a carriage return
print("\"Welcome to Edpresso!\""); // a double quote
print("\'Welcome to Edpresso!\'"); // a single quote
print("\\Welcome to Edpresso!\\"); // a backward slash

Explanation

  • Lines 2–7: We print some strings with some escape sequences in them.

Free Resources