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 ("
):
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:
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:
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:
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:
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 "#
):
#"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 """#
:
#"""
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:
##"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:
#"""
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:
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:
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:
let player = "Bob"
let score = 952
print("Hi \(player), your score is: \(score).")
This is much easier than using concatenation:
print("Hi " + player + ", your score is: " + String(score) + ".")
In a raw string literal, interpolation requires an extended escape character, just like special characters:
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.