Standard strings in Swift open and close with double quotes, but they cannot contain actual line breaks (by hitting Enter). For example, here is a standard string:
Swift
var quote = "I will code hard and become a great developer."
This works fine for short snippets of text, but if the text you want to store is long, it becomes ugly and hard to read in your source code. That is why we use multi-line strings.
How to Use Multi-line Strings
By using triple double quotes ("""), you can write a string across as many lines as you need. This makes the text much easier to read inside your codebase.
Swift
var harrtPotter = """
You're a wizard, Harry.
I'm a what?
A wizard. And a thumping good one, I'd wager.
"""
Because Swift treats the line breaks in your code as part of the text itself, the stored string actually contains three distinct lines.
Excluding Line Breaks from the String Data
If you want to format your code neatly across multiple lines for readability, but do not want those line breaks to actually appear in the final text data, end each line with a backslash (\):
Swift
var longSentence = """
This is a very long sentence that I want to write \
across multiple lines in my code editor, but it will \
print out as a single continuous line.
"""
Why Should You Use Multi-line Strings?
Sometimes you might be tempted to cram a very long piece of text into a single-line string, but this is rarely a good idea. Using proper multi-line strings is especially crucial when sharing code or collaborating with others.
One practical reason is debugging: if your program throws a long error message or displays a block of text, you will often need to search (Ctrl + F or Cmd + F) your codebase to find where that text originated. If the text is messily concatenated or hidden in a giant horizontal line, your search might fail. Multi-line formatting keeps your searchable text structured and clean.
Incorrect Code Examples
Important Rule: The opening and closing triple double quotes (""") must be on their own separate lines.
Swift
// WRONG: Standard double quotes cannot contain line breaks.
var starWars = "Help me, Obi-Wan Kenobi.
You're my only hope."
// WRONG: A long string on one line is bad for readability and collaboration.
var loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam."
// WRONG: The text cannot start on the same line as the opening """
var steveJobs = """Stay hungry.
Stay foolish."""
// WRONG: The closing """ cannot be on the same line as the text.
var terminator = """
I'll be back."""
댓글
댓글 쓰기