Skip to content

Strings ​

So far, your programs have only used numbers as data. In this chapter, you’ll learn how to use text.

String ​

Programmers refer to textual data as strings. That may seem odd, but to a programmer, text is merely a sequence β€” or string β€” of characters.

The easiest way to create a string is to write a string literal, which is a piece of text wrapped in double-quotes ("):

swift
let author = "Steven"
let feedback = "We ❀ Swift!"

Swift infers the type of these constants as String, which is the type that represents text.

Character ​

Type Character represents a single character. Characters don’t have their own literals; you just use a string literal that contains a single character:

swift
let check: Character = "βœ“"

The type annotation is required here because type inference prefers String over Character.

Swift uses the Unicode character set with UTF-8 encoding. This means each Unicode character takes up one to four bytes. However, in some cases, a single Character consists of multiple Unicode characters. For example:

swift
let ok: Character = "πŸ‘ŒπŸΎ"

This character is a combination of the OK sign emoji with a skin tone modifier, each of which requires four bytes.

Note

On Windows, some characters (such as emojis) may not display properly in your terminal.

Special characters ​

The backslash character (\) has a special meaning in string literals. It serves as an escape character that indicates the start of a special character combination.

Here are some of the special characters you can use in string literals:

  • \n inserts a line break.
  • \t inserts a tab.
  • \" inserts a double quote.
  • \\ inserts a regular backslash.

The following example uses these characters in a string:

swift
let highscores = "1.\tACE\t976\n2.\tBOB\t952\n3.\tCU2\t897"
print(highscores)

let quote = "\"If you tell the truth, you don’t have to remember any lies.\""
print(quote)

let projectsDirectory = "C:\\Projects\\Swift\\"
print(projectsDirectory)

Run this code and observe its output to see the special characters in action.

Multiline strings ​

A multiline string literal contains text that spans multiple lines. Compared to a regular string literal, which must be on a single line and use \n to insert line breaks, a multiline literal is much easier to read.

The following example uses a multiline string literal to print the table of high scores from the previous example:

swift
print("""
  1.\tACE\t976
  2.\tBOB\t952
  3.\tCU2\t897
  """)

As you can see, a multiline string literal starts and ends with three double-quotes. The line breaks after the opening quotes and before the closing quotes are required and aren’t part of the string.

The indentation of the closing quotes determines the indentation of the content. In this example, the closing quotes have two spaces of indentation. As a result, the first two spaces of each line are ignored and aren’t part of the string.

Raw strings ​

A raw string literal can include characters such as \ or " directly, without having to escape them as \\ or \". Raw string literals use extended delimiters (#" and "#):

swift
#"Use \t to insert a tab."#

In this string, the characters \ and t are part of the string. They don’t insert a tab character.

For multiline literals, the extended delimiters are #""" and """#:

swift
#"""
Use \t to insert a tab. The following example:

print("\tHello")

prints:

    Hello
"""#

You can increase the amount of number signs in the delimiters, as long as they remain balanced. The following string includes the character combination "#, so its delimiters require an additional number sign:

swift
##"Use #" and "# to delimit a raw string."##

Raw string literals can include special characters by extending the escape character (\) with the same amount of number signs as the delimiters. The following string uses the character combination \#t to insert a tab character:

swift
#"""
Use \t to insert a tab. The following example:

print("\tHello")

prints:

\#tHello
"""#

Concatenation ​

You can use the + and += operators to join strings together. This operation is known as concatenation:

swift
let file = "main.swift"
let path = projectsDirectory + file
print(path)

var name = "Bond"
name += ", James Bond"
print(name)

Like their numeric counterparts, these operators require two operands of the same type β€” in this case, String. You must use type conversion to concatenate a character with a string:

swift
String(check) + file

Interpolation ​

String interpolation is a way to build complex strings by adding in the values of expressions. You do this by wrapping the expression in parentheses and escaping it with a backslash. Swift will then evaluate the expression and convert its value to a string:

swift
let player = "Bob"
let score = 952
print("Hi \(player), your score is: \(score).")

This is much easier than using concatenation:

swift
print("Hi " + player + ", your score is: " + String(score) + ".")

In a raw string literal, interpolation requires an extended escape character, just like special characters:

swift
print(#"Hi \#(player), your score is: \#(score)."#)

Up next ​

Strings can do much more than what’s been covered in this chapter. You’ll discover some of their advanced features later in this course, as you learn more about Swift.

In the next chapter, you’ll learn about control flow statements and how they influence the execution of your code.