Swift - String Escape Characters

Introduction

String literals can contain one or more characters that have a special meaning in Swift.

To represent the double quote " within a string, prefix the double quote with a backslash \

Demo

var quotation = "Albert Einstein: \"A  person who never made a mistake never tried anything new \" "
print(quotation)

Result

To represent the single quote ' within a string, simply include it in the string:

Demo

var str = "'A' for Apple"
print(str)

Result

To represent the backslash \ within a string, prefix the backslash with another backslash \

Demo

var path = "C:\\WINDOWS\\system32"
print(path)

Result

The \t special character represents a tab character:

Demo

var headers = "Column 1 \t Column 2 \t Column3"
print(headers)

Result

The \n special character represents a newline character:

Demo

var column1 = "Row 1\nRow 2\nRow 3"
print(column1)

Result

Related Topic